Я проверяю некоторую проверку в моем контроллере. И я хочу добавить ошибку к конкретному элементу моей формы при ошибке. Моя форма:
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'));
Как элементы формы также имеют тип 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;
}
}