Answer the question
In order to leave comments, you need to log in
How to validate ajax form and get errors in symfony?
Hello!
The registration form is rendered by react and submitted by an AJAX request, but after I do $form->submit(...) , $form->getErrors() doesn't return any errors even though $form->isValid() === false . If you render the form $form->createView(); then everything works.
Questions:
1. How can you validate a form without creating your own validator with an ajax request, the form is rendered by react, not $form->createView();
2. How can I generate a Symfony\Component\HttpFoundation\Request to pass it to $form->handleRequest($request); based on data that comes fromAn AJAX request , roughly speaking that $reques t be the same as a normal form submission when the form is rendered by the $form->createView() server.
entity:
use Symfony\Component\Validator\Constraints as Assert;
class RegisterData
{
/**
* @var string
* @Assert\NotBlank()
* @Assert\Email()
*/
public $email;
/**
* @var string
* @Assert\NotBlank()
* @Assert\Length(min=6)
*/
public $password;
}
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RegisterDataForm extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('email', Type\EmailType::class)
->add('password', Type\PasswordType::class)
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => RegisterData::class,
]);
}
}
public function request(Request $request, SignUp\Request\Handler $handler, Validator $validator): Response
{
$data = new RegisterData();
$form = $this->createForm(RegisterDataForm::class, $data, ['csrf_protection' => false]);
if($request->isXmlHttpRequest()) {
// $request->request->set($form->getName(), $request->request->all());
// $form->handleRequest($request); // так тоже не работает
$form->submit($request->request->all());
// $form->isValid() === false
// $form->getErrors() - пустой
...
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question