Symfony 形式继承:属性 和其中一种方法都不存在

Symfony form inheritance : Neither the property nor one of the methods exist

我有一个嵌套表单

demand
    home
       child
       godfather

demand 是父级并嵌入 home 嵌入 childfather(最后两个形式在同一级别)

DemandeType我有:

           $builder
           ->add('date', 'datetype')
           ->add('name', 'text')
           //...

           ->add('home', 'home', array(
            'mapped' => false,
            'data_class' => 'AppBundle\Entity\Home',
            'inherit_data' => true
             ))

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Demand',
    ));
}

HomeType中:

           $builder
           ->add('address', 'textarea')
           //...

           ->add('child', 'child', array(
            'mapped' => false,
            'data_class' => 'AppBundle\Entity\Child',
            'inherit_data' => true
             ))

           ->add('godfather', 'godfather', array(
            'mapped' => false,
            'data_class' => 'AppBundle\Entity\Godfather',
            'inherit_data' => true
             ))

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Home',
    ));
}

而在 ChildTypeGodfatherType 中,我只有名字和姓氏的文本字段以及他们的权利 data_class。

但是当我提交表单(DemandType,其中嵌入了所有子表单)时出现了这个错误:

Neither the property "address" nor one of the methods "getAddress()", "address()", "isAddress()", "hasAddress()", "__get()" exist and have public access in class "AppBundle\Entity\Demand".

并且这些方法不属于 Demand 实体,而是属于 Home 实体。我已经放了 inherit_data,我缺少什么?

谢谢

发生这种情况是因为您正在使用 inherit_data。 属性 使表单将整个提交的数据传递给它的子节点,而不是默认情况下发生的单个 属性(或来自 getter 函数的任何内容)。

您对 demandhome 都执行此操作,这就是 home 表单类型接收实例 Demand 实体的原因。所以我猜您想从 home 中删除 inherit_data 并只使用:

->add('home', 'home', array(
    'mapped' => false,
    'data_class' => 'AppBundle\Entity\Home',
))

在这种情况下,home 将从 $demand->getHome() 接收数据,这应该是一个 Hone 实体。

我不确定您是否真的需要使用 inherit_data,但这取决于您的用例。通常,您不需要它,因为您具有实体结构,例如:

/** @ORM\Entity() */
class Demand {
    /** @ORM\OneToWhatever() */
    private $home;
    public function getHome() {
        return $this->home;
    }
}

/** @ORM\Entity() */
class Home {
    /** @ORM\OneToWhatever() */
    private $child;
    public function getChild() {
        return $this->child;
    }
}

/** @ORM\Entity() */
class Child { ... }

但是我不知道你的数据结构到底是什么,所以很难帮上忙。

此外,您正在使用 mapped => false,我不确定这是您想要的,因为它会阻止 Symfony 使用表单数据更新实体。

参见: