将错误添加到Symfony 2表单元素


Add error to Symfony 2 form element

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

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元素?

您可以进行

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

As形式元素也是FormInterface类型的。

好吧,伙计们,我有另一种方法。它更为复杂,而且只针对特定的情况。

我的案例:

我有一个表格,提交后我发布数据到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;
    }
}