I am using Symfony Form 4.2 in standalone way. I have a form element with few fields in HTML file. To have validation in PHP as well, I replicated the form in PHP using Symfony Form 4.2 like below:
$formFactory = Forms::createFormFactoryBuilder()
->addExtension(new ValidatorExtension($validator))
->getFormFactory();
$form = $formFactory->createBuilder()
->add('pk_firstname', TextType::class, [
'constraints' => [new NotBlank(),
new Length([
'min' => 2,
'max' => 50,
'minMessage' => 'Your first name must be at least {{ limit }} characters long',
'maxMessage' => 'Your first name cannot be longer than {{ limit }} characters']
)],
])
->add('pk_lastname', TextType::class, [
'constraints' => [new NotBlank(),
new Length([
'min' => 2,
'max' => 50,
'minMessage' => 'Your first name must be at least {{ limit }} characters long',
'maxMessage' => 'Your first name cannot be longer than {{ limit }} characters']
)],
])
->add('pk_emailaddress', EmailType::class, [
'constraints' => [new NotBlank(), new Email(
[
'message' => 'The email "{{ value }}" is not a valid email.',
'mode' => 'strict',
]
)],
])
->add('pk_phonenumber', TelType::class, [
'constraints' => [],
])
->add('pk_message', TextareaType::class, [
'constraints' => [new NotBlank()],
])
->getForm();
When the form is submitted in the frontend, I prevent default behaviour by using JavaScript and make a AJAX request to PHP file with submitted data where Symfony form is used to validate correctness of submitted data.
Then, I manually submit the form like below:
$request = Request::createFromGlobals();
$submitData = array("pk_firstname" => $request->request->get('pk_firstname'),
"pk_lastname" => $request->request->get('pk_lastname'),
"pk_emailaddress" => $request->request->get('pk_emailaddress'),
"pk_phonenumber" => $request->request->get('pk_phonenumber'),
"pk_message" => $request->request->get('pk_message'));
$form->submit($submitData);
The problem here is, upon invalid data are submitted isValid()
method on $form
object return the form is not valid but getErrors()
methods return empty array.
Is there something I do wrongly here?
I'd like to get fields which violated the constraints and which constraints so that I can pass those error messages to JavaScript to display in the frontend.