Question

My Symfony 1.4 application "Edit" menu very slow. When I click on edit link it takes almost 2 minutes to response.

I am using the following function in my module's action.class.php file.

public function executeNew(sfWebRequest $request) {
    $this->form = $this->configuration->getForm();
    $this->employee_attendance = $this->form->getObject();
}
Was it helpful?

Solution

There is a common pitfall when using automatically generated forms in Symfony. When your form has a field which is a foreign key of a related model then a <select> element is created for this element. All the possible values of the related values are fetched from the database and populated as objects. Then the __toString() method is used on each object to display a user friendly value on the list. If the implementation of this function uses another related object then the relation is read from the database for each object separately.

For example, if you have in your form a field for related object Shift and the __toString method in the Shift class refers to another model, let's say:

function __toString()
{
    return sprintf(
        '%s - %s',
        $this->getShiftType()->getName(),
        $this->getName()
    );
}

Then the ShiftType will be fetched from the database one by one for each Shift. If your select lists several thousands shifts you will have the same amount of database queries run each time you open the form (not to mention resources needed to hydrate objects).

There are two things that can be done to solve the problem:

  • usually the related object is set in some other way than being chosen by the user so you can just skip the widget altogether. Something like unset($this['shift_id']); in your form's setup function.

  • If you do need the select use a specific table method where you will limit the number of elements retrieved from the DB and/or join with any relevant tables (the ShiftType in our example). You can add an option to the widget in your form:

    $this->widgetSchema['shift_id']->addOption(
        'tableMethod', 
        'yourFunctionRetrievingJoinedTables'
    );
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top