根据Symfony2中提交的数据添加必填表单字段

时间:2014-05-15 11:22:14

标签: php forms symfony symfony-2.4

我有一个状态选择的表单。如果选择了某个状态并提交了表单,则应重新加载并需要一个额外的字段。

我已经阅读了Dynamic generation for submitted Forms以及互联网上几乎所有其他帖子以及有关此主题并尝试了不同的事件组合(并且遇到了不同的错误),但我仍然很难使其正常工作。

这是我到目前为止所做的:

FormType

private function addProcessAfterField(FormInterface $form)
{
    $form->add('processAfterDate', 'date', array('required' => true));
}


public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('status', 'entity', array(
        'class' => 'Acme\Bundle\ApplicationBundle\Entity\LeadStatusCode',
        'choices' => $this->allowedTypes
    ));

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){

        $form = $event->getForm();
        $data = $event->getData();

        if ($data->getStatus()->getId() == LeadStatusCode::INTERESTED_LATER) {
            $this->addProcessAfterField($form);
        }
    });

    $builder->get('status')->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event){
        $data = $event->getData();
        if ($data == LeadStatusCode::INTERESTED_LATER && !$event->getForm()->getParent()->getData()->getProcessAfterDate()) {
            $this->addProcessAfterField($event->getForm()->getParent());
        }
    });

    $builder->add('comment', 'textarea', array('mapped' => false));
    $builder->add('Update', 'submit');
}

错误:

ContextErrorException: Catchable Fatal Error: Argument 1 passed to Proxies\__CG__\Acme\Bundle\ApplicationBundle\Entity\Lead::setProcessAfterDate() must be an instance of DateTime, null given, called in /var/www/application.dev/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 360 and defined in /var/www/application.dev/app/cache/dev/doctrine/orm/Proxies/__CG__AcmeBundleApplicationBundleEntityLead.php line 447

如上所述,我尝试了不同的事件组合,其中一个几乎正在工作但是日期从未持久保存到实体,因此我将\ DateTime类型提示添加到setProcessAfterDate()方法。我不确定我是否正确理解事件系统或错误是否在其他地方。

1 个答案:

答案 0 :(得分:0)

嗯,这可能不是解决问题的最佳方式,但总而言之:

$form->handleRequest($request);

if($form->isValid()) // check if the basic version of the form is ok
{
     $form = $this->createForm(new XXXXForm(), $form->getData()); // you recreate the form with the data that was submitted, so you rebuild the form with new data

     if($form->isValid())
     {
           // ok
     }



  // not ok
}

然后在buildForm函数中,根据您的需要,根据字段的“必需”属性值进行基础:

'required' => $this->getCheckRequired($options)


private function getCheckRequired($options) // checks whether field should be required based on data bound to the form
{
  if($options && isset($options['data'])
  {

    switch $options['data']->getStatus():
       // whatever

    ;
  }

return false;

}  

正如我所说,这不是最好的解决方案,它不会修复你的方法,而是提出一个不同的方法,但它可以完成工作