Reputation: 135
I have a strange problem.
My form is valid by symfony even if the provided data are not. This form is created and posted by ajax requests (it this can affect it)
if(!$request->isXmlHttpRequest()){
return new JsonResponse(['code' => 403], 403);
}
$name = $request->query->get('name');
$contact = new Contact();
$contact->setName($name);
$form = $this->get('form.factory')->create(ContactType::class, $contact);
if($request->isMethod('POST')){
$form->submit($request);
if($form->isValid()){
$em = $this->get('doctrine.orm.entity_manager');
$em->persist($contact);
$em->flush();
return new JsonResponse(['code' => 200, 'id' => $contact->getId(), 'name' => $contact->getName()]);
}
return new JsonResponse(['formView' => $this->renderView('@MyBundle/Contacts/contactForm.html.twig',['form' =>$form->createView()]), 'code' => 400, 'errors' => $form->getErrors(true)]);
}
return new JsonResponse(['formView' => $this->renderView('@MyBundle/Contacts/contactForm.html.twig',['form' =>$form->createView()]), 'code' => 200], 200);
With data looking like this (retvrieved with xdebug):
'id' => NULL,
'name' => NULL,
'companyId' => NULL,
'companyTaxId' => NULL,
'birthNumber' => NULL,
'phoneLandLine' => NULL,
'phoneMobile' => NULL,
'phoneFax' => NULL,
'email' => NULL,
'www' => NULL,
Problem is, that name, which is set as required, is null, even though form is marked as valid and there are no errors. After this, there is a doctrine exception about missing required field.
Do you have any clue why this should happen?
Symfony v2.8.10, Doctrine v1.6.4
Upvotes: 1
Views: 1865
Reputation: 1674
Probably, validation is not enabled for "name" field. To enable it - add NotBlank annotation to your entity:
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255)
*
* @Assert\NotBlank()
*/
private $name;
http://symfony.com/doc/current/reference/constraints/NotBlank.html
Or add constraint directly to the form:
$builder
->add('name', TextType::class, [
'constraints' => [
new \Symfony\Component\Validator\Constraints\NotBlank(),
],
])
Upvotes: 1
Reputation: 340
The required attribute does not act as a validator. Quoting from http://symfony.com/doc/2.8/reference/forms/types/text.html#required
If true, an HTML5 required attribute will be rendered. The corresponding label will also render with a required class.
This is superficial and independent from validation. At best, if you let Symfony guess your field type, then the value of this option will be guessed from your validation information.
Take a look at http://symfony.com/doc/2.8/forms.html#form-validation
Upvotes: 0