【问题标题】:Add error to Symfony 2 form element向 Symfony 2 表单元素添加错误
【发布时间】:2012-09-07 07:48:38
【问题描述】:

我在我的控制器中检查了一些验证。我想在失败时将错误添加到表单的特定元素中。我的表格:

use Symfony\Component\Form\FormError;

// ...

$config = new Config();
$form = $this->createFormBuilder($config)
        ->add('googleMapKey', 'text', array('label' => 'Google Map key'))
        ->add('locationRadius', 'text', array('label' => 'Location radius (km)'))
        ->getForm();

// ...

$form->addError(new FormError('error message'));

addError() 方法将错误添加到表单,而不是元素。如何向 locationRadius 元素添加错误?

【问题讨论】:

    标签: php validation symfony symfony-forms


    【解决方案1】:

    你可以的

    $form->get('locationRadius')->addError(new FormError('error message'));
    

    因为表单元素也是FormInterface 类型。

    【讨论】:

    • @m2mdas,很好的答案!我们将如何翻译这个?因为一旦我们创建了一个 FormError 实例,它就不会翻译它,对吗?我试过了,它没有翻译它,我认为这是有道理的。您将如何翻译 FormError 实例?
    • 您好@Patt,抱歉回复晚了。 Validator 组件负责在将错误消息添加到表单之前翻译表单约束违规消息。要添加自定义错误,您必须以与其他字符串相同的方式翻译消息,例如 $this->get('translator')->trans('error message')
    • @m2mdas 但是如何在视图中打印此错误?我试过这个,但它没有进入我的树枝中的form_errors(form)
    • @NatNaydenova 我知道已经有一段时间了,但试试form_erros(form.my_field_name)
    • 请注意:要使用 form_errors(form) 打印错误,请将您的错误添加到表单本身,例如$form->addError(new FormError('error msg');
    【解决方案2】:

    好的,伙计们,我有另一种方法。它更复杂,仅适用于特定情况。

    我的情况:

    我有一个表单,提交后我将数据发布到 API 服务器。还有我从 API 服务器得到的错误。

    API 服务器错误格式为:

    array(
        'message' => 'Invalid postal code',
        'propertyPath' => 'businessAdress.postalCode',
    )
    

    我的目标是获得灵活的解决方案。让我们为相应的字段设置错误。

    $vm = new ViolationMapper();
    
    // Format should be: children[businessAddress].children[postalCode]
    $error['propertyPath'] = 'children['. str_replace('.', '].children[', $error['propertyPath']) .']';
    
    // Convert error to violation.
    $constraint = new ConstraintViolation(
        $error['message'], $error['message'], array(), '', $error['propertyPath'], null
    );
    
    $vm->mapViolation($constraint, $form);
    

    就是这样!

    注意! addError() 方法绕过 error_mapping 选项。


    我的表格(公司表格中嵌入的地址表格):

    公司

    <?php
    
    namespace Acme\DemoBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\Validator\Constraints;
    
    class Company extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('companyName', 'text',
                    array(
                        'label' => 'Company name',
                        'constraints' => array(
                            new Constraints\NotBlank()
                        ),
                    )
                )
                ->add('businessAddress', new Address(),
                    array(
                        'label' => 'Business address',
                    )
                )
                ->add('update', 'submit', array(
                        'label' => 'Update',
                    )
                )
            ;
        }
    
        public function getName()
        {
            return null;
        }
    }
    

    地址

    <?php
    
    namespace Acme\DemoBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\Validator\Constraints;
    
    class Address extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                // ...
                ->add('postalCode', 'text',
                    array(
                        'label' => 'Postal code',
                        'constraints' => array(
                            new Constraints\NotBlank()
                        ),
                    )
                )
                ->add('town', 'text',
                    array(
                        'label' => 'Town',
                        'constraints' => array(
                            new Constraints\NotBlank()
                        ),
                    )
                )
                ->add('country', 'choice',
                    array(
                        'label' => 'Country',
                        'choices' => $this->getCountries(),
                        'empty_value' => 'Select...',
                        'constraints' => array(
                            new Constraints\NotBlank()
                        ),
                    )
                )
            ;
        }
    
        public function getName()
        {
            return null;
        }
    }
    

    【讨论】:

    • 你把这些代码放在哪里? $vm = new ViolationMapper();
    • @vidyvideni,将处理表单提交的控制器操作。您也可以调整这段代码并将其移至单独的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-24
    • 2013-12-07
    相关资源
    最近更新 更多