I have Symfony form with PRE_SUBMIT
listener.
The listener checks string format for one field.
class TestEntType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('someText', TextType::class, ['error_bubbling' => false]);
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$data = $event->getData();
$form = $event->getForm();
...
if (false === $this->isFormattedCorrectly($data['someText'])) {
$form->get('someText')
->addError(new FormError('Text format should be...'));
}
});
}
...
}
If the listener is written this way - form is valid, even if I force adding error every single time. It seems that error is somewhere overwritten or deleted.
But if I make small change, and convert $form->get('someText')->addError(..)
to $form->addError(..)
, form isn't valid any more.
If I dump (string)$form->getErrors(true)
in the controller, I get ERROR: Text format should be...
So, the error isn't lost in this situation.
But the problem is that this error isn't bounded to someText
field!
This is the controller:
class TestEntController extends Controller
{
/**
* @Route("/test-ent", name="test-ent")
* @Method("POST")
*/
public function testAction(Request $request)
{
$testEnt = new TestEnt();
$form = $this->createForm(TestEntType::class, $testEnt);
$data = json_decode($request->getContent(), true);
if ($data === null) {
//...
}
$form->submit($data);
if (!$form->isValid()) {
// ...throw $this->throwApiProblemValidationException($form);
}
$em = $this->getDoctrine()->getManager();
$em->persist($testEnt);
$em->flush();
return new JsonResponse($testEnt);
}
}
Has someone idea where error disappears when I bound it to the specific field?
Is possible to bound error to the specific field in PRE_SUBMIT
form listener?
Is there some smarter way to check is string formatted correctly?
- I was following directions from this SO question Add error to Symfony 2 form element
EDIT: It seems that everything normally works if I listen for FormEvents:: SUBMIT
event. In that case, error isn't lost.
To figure out what is happening, I'll have to in detail investigate how Symfony form works...