【问题标题】:Symfony check form field exist inside controllerSymfony 检查表单字段存在于控制器中
【发布时间】:2015-09-29 10:38:50
【问题描述】:

有没有办法检查控制器中是否存在表单字段?

我有几个提交按钮,但根据对象中的数据,将显示和创建关联的按钮。

FormType.php

$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
    /** @var ObjectInfo $tab */
    $tab = $event->getData();
    $form = $event->getForm();

    if (some condition) {
        //No Value has been set or NULL
        $form->add('submit_second', 'submit', array(
            'label' => 'submit',
        ))
    }

controller.php

 if ($overviewForm->get('submit_second')->isClicked()) {
     // do something
 }

我也试过了

if (
    !is_null($overviewForm->get('submit_second')) && 
    $overviewForm->get('submit_second')->isClicked()
) {

提交时我得到

错误

Child "submit_second" does not exist.

【问题讨论】:

  • 只是猜测:if ($overviewForm->has('submit_second')) {...}

标签: forms symfony


【解决方案1】:

如果$form->has('field')@jahller 建议)不起作用,您可以尝试将“some condition”的逻辑放入实体/模型的方法中,然后调用该方法你需要的地方。

您应该可以在 FormTypeController 中访问您的模型/实体。

【讨论】:

【解决方案2】:

您也可以使用try catch。我实际上不确定何时引入了 OutOfBounds 异常。但我在 3.4 中使用它

try {
    $field = $form->get('nonExistantChild');
    // Then you know the field exists
} catch (Symfony\Component\Form\Exception\OutOfBoundsException $e) {
    // Field doesn't exists.
}

【讨论】:

    【解决方案3】:

    您可以改为处理数据,因为大多数时候您仍然需要它。

    if (!array_key_exists('nonExistantChild', $data = $event->getData())) { 
        // No need to do anything then
        return; 
    }
    
    // Can now do something with $data then
    

    【讨论】:

      猜你喜欢
      • 2017-09-09
      • 1970-01-01
      • 1970-01-01
      • 2020-03-01
      • 2017-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多