所以我在两个实体之间有grails:
plugin:
springsecurity:
active: true
useSecurityEventListener: false
关系并且我已经创建了相关的表单,但似乎OneToMany
在发送数据之后看不到实体的子节点。
家长班:
FormBuilder
儿童班:
class Parent{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="Child",mappedBy="parent",cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $children;
}
这是FormTypes:
class Child{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="Parent", inversedBy="children")
*/
private $parent;
}
子FormType:
class ParentType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')
->add('children', CollectionType::class, array(
'entry_type' => ChildType::class,
'allow_add' => true
));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Parent'
));
}
}
之后我在控制器中创建了我的表单,如下所示:
class ChildType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Child'
));
}
}
当然我正在使用symfony function saveAction(Request $request){
$parent = new Parent();
$form = $this->createForm('Bundle\Form\ParentType', $parent);
$form->handleRequest($request);
if ($form->isSubmitted()) {
//--after submitted the form I just want to display the children
die(var_dump($parent->getChildren()));
}
}
提供的数据原型中的jquery创建子项,但表单看不到它们!
我在这里缺少什么?
答案 0 :(得分:0)
可能是因为你的'二传手'没有被召唤。
尝试添加by_reference
并将其设置为false
,如下所示:
class ParentType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')
->add('children', CollectionType::class, array(
'entry_type' => ChildType::class,
'allow_add' => true,
'by_reference' => false
));
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Parent'
));
}
}
我没时间实际测试您的代码。但是,您不必将parent
放在child
表单中。所以你的孩子formType应如下所示:
class ChildType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name') ;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Bundle\Entity\Child'
));
}
}
希望它有所帮助。