访问(在Controller中)一个嵌套在表单集合中的未映射字段

时间:2015-04-09 12:18:02

标签: php forms symfony

在表格中,我在答案的集合中嵌入了删除复选框。 (每个答案都有一个删除复选框,以便我可以轻松删除任何答案)

但我没有成功从控制器访问删除值

这里的代码: 首先,我使用答案

填充表单
 $Answers = $repository->liste_Answers_Child_Of_A_Question($question); // return a list of answers  
 $Answers = array('Answers' => $Answers);
 $form = $this->createform(new AnswersType(),$Answers);

AnswersType(带有s)

$builder->add('Answers','collection', array('type'=> new AnswerType()));

AnswerType

$builder->add('Answer_text','text')
        ->add('delete','checkbox',array(
              'mapped'=> false,))

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array('data_class' => 'Site\BlogBundle\Entity\Answer'))
}

PS:我不想使用' allow_delete'选项与jquery相结合。

1 个答案:

答案 0 :(得分:0)

您可以随时在“复选框”字段中附加“数据”属性,如下所示:

$builder->add('Answer_text','text')
        ->add('delete','checkbox',array(
              'mapped'=> false,
              'data' => $options['data'] instanceof Answer ? $options['data']->getId() : true // where $options['data'] is your Answer entity. In case you have a "create" action for this type, $options['data'] is null, so we provide 'true' as an alternative
            )
        )

在此之后,在$ form-> handleRequest($ request)之后的控制器中,在$ answer对象中,您可以执行$ answer-> getDelete(),它将返回答案ID。

如果您需要更多帮助,请告知我们 P.S。:也可以通过FormEvents :: POST_SET_DATA事件使用表单事件来实现。

编辑:清洁解决方案

如上所述,您可以使用如下所述的事件监听器,而不是信任表单类型来为您提供数据:
首先,从构建器中删除“删除”字段,并仅保留“answer_text”。然后,通过表单侦听器(FormEvents :: PRE_SET_DATA)创建“删除”字段,如下所示:

$builder->add('answer_text' ...); // initialy, you don't add the delete button

// then, when the form is populated with data, you also add the delete functionality
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) use ($builder)
  {
    $form = $event->getForm(); // this is your form builder
    $data = $event->getData(); // this is your data entity, aka Answer

    /* Check we're looking at the right data/form */
    if ($data instanceof Answer)
    {
        $answerId = $data->getId(); // here, you no longer have to validate the id. It is automaticaly set to null by the data binding provided by the form.

        $form->add('delete', 'checkbox', [
            'mapped'=> false,
            'data' => $answerId
        ]);
    }
  });
}

如果这对您有用,请告诉我。