1

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

我已经阅读了提交表单的动态生成以及互联网上几乎所有其他关于该主题的帖子,并尝试了不同的事件组合(并且得到了不同的错误),但我仍然努力使其正常工作。

这是我到目前为止所拥有的:

表单类型

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() 方法。我不确定我是否没有正确理解事件系统,或者错误是否存在于其他地方。

4

1 回答 1

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;

}  

正如我所说,这不是最好的解决方案,它并不能解决您的方法,而是提出了一个不同的方法,但它可以完成工作

于 2014-05-15T12:58:50.547 回答