Symfony 2.8 - 一对一表单类型,提交后空关系数据为空

时间:2018-04-12 08:42:56

标签: symfony symfony-forms symfony-2.8

我有两个表格,两个实体有一对一的关系:

class RelationTwoType ...{
      public function buildForm(...){
             $builder
                 // Problem here: these are empty
                 ->add('some_property_1')
                 ->add('some_property_2')
      }

      public function configureOptions(OptionsResolver $resolver)
      {
           $resolver->setDefaults(array(
              'data_class' => RelationTwo::class,
           ));
      }
}

class RelationType ...{
      public function buildForm(...){
             $builder->add('relationTwo', RelationTwoType::class)
      }

      public function configureOptions(OptionsResolver $resolver)
      {
           $resolver->setDefaults(array(
              'data_class' => Relation::class,
           ));
      }
}

但是,当我尝试提交此嵌套表单时,数据为空?我不知道为什么会这样。控制器逻辑如下所示:

    $relation = new Relation();
    $relationTwo = new RelationTwo();
    $relation->setRelationTwo($relationTwo);

    $form = $this->createForm(RelationType::class, $relation);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()){
        $relation = $form->getData();
        // this is empty for the nested relation
        dump($form->getData());
        die();
        $em = $this->getDoctrine()->getManager();
        $em->persist($relation);
        $em->flush();
    }

    // No errors
    dump($form->getErrorsAsString());
    die();

1 个答案:

答案 0 :(得分:0)

试试这个:

class RelationsType ...{
  ->add('RelationTwo', RelationTwoType::class)
  ->add('some_property_1')
  ->add('some_property_2')
}
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
       'data_class' => Relation::class,
     ));
 }

一个简单的$relation = $form->getData();应该起作用

祝你好运