Search code examples
phpformsvalidationsymfony

Symfony 2.3 validating form with handleRequest is insanely slow


I am submitting a form with a lot of fields and trying to validate it with handleRequest($request) as it is shown in the Symfony documentation. My entity is very big and has a lot of relations with other entities. handleRequest($request) is validating each form field submitted and checking for errors.

The problem found is while submitting an id of a related entity of my main entity (in example a person of an office), handleRequest will internally get all objects of the related entity (the full table of the related entity, all persons) and hydrating them as objects.

I think it should just check if the submitted id exists in the other table, get that related entity object and check it for errors (instead of getting all the related table).

If you check and debug the source code of Symfony2 handleRequest, you may easily spot the same problem at this lines:

Form/Form.php

// Normalize data to unified representation
$normData = $this->viewToNorm($viewData);
$value = $transformers[$i]->reverseTransform($value);

How can I still validate the form without dealing with this issue which makes it insanely slow to validate a form with handleRequest($request)?

If I don't use handleRequest to validate it, which automatically add the errors to my form for each field, how could I manually validate each field and later add the errors to my form for each field and show them in the next view?


Solution

  • This question is a little vague, and the answer very much depends on your specific form. Please post the form definition that is giving you the hardest time.

    Check to make sure that you are not EAGER fetching associations here.

    handleRequest() is going to take the request object and construct the model that your form describes, as your form defined it to.

    If the objects are required in order to display data on your initial form to the user, or to validate the data on submit, the "entity" field type will fetch all of the objects you told it to in its definition. If you are displaying a big select list, for example, all of this data is needed.

    I had a similar problem in the past and it was because I was using a lot of choice fields that were being used as a series of multiple select checkboxes. My bottleneck was actually in the twig layer while rendering out the thousands of checkboxes I had stored as separate entities.

    I switched from a set of checkboxes to a single multi-select box and it increased my speed significantly.