Validation of a form before submission

2020-04-21 04:46发布

问题:

Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want the form to be validated before the form is submitted.

I followed this entry of the cookbook :

$form = $this->container->get('form.factory')->create(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
    ...
}

But the form is not populated with the entity datas : all fields are empty. I tried to replace $request->request->get($form->getName()) with $myEntity, but it triggered an exception :

$myEntity cannot be used as an array in Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php

Does anyone know a method to feed the submit method with properly formatted datas so I can achieve my goal ? Note : I don't want Javascript to be involved.

回答1:

In place of:

$form->submit($request->request->get($form->getName()));

Try:

$form->submit(array(), false);


回答2:

You need to bind the the request to the form in order to fill the form with the submitted values, by using: $form->bind($request);

Here is a detailed explanation of what your code should look like:

//Create the form (you can directly use the method createForm() in your controller, it's a shortcut to $this->get('form.factory')->create() )
$form = $this->createForm(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));

// Perform validation if post has been submitted (i.e. detection of HTTP POST method)
if($request->isMethod('POST')){

    // Bind the request to the form
    $form->bind($request);

    // Check if form is valid
    if($form->isValid()){

        // ... do your magic ...

    }

}

// Generate your page with the form inside
return $this->render('YourBundle:yourview.html.twig', array('form' => $form->createView() ) );