Search code examples
databasevalidationformssymfony1doctrine

Symfony 1.4 Checking form values against database entries before saving


I am working with Symfony 1.4 and Doctrine. I have a form that has six fields: name, parent1, parent2, parent3, parent4, parent5 Once the form is submitted I want to check the database for two things: 1. The name field is unique 2. That the combination of parent1, parent2, parent3, parent4, and parent5 is not already in the database. These values are all integers (primary keys from a related table), some fields are left blank as 0. They are going into the database based on the order in which the user inputs it, so I do not care about the order, but would like to make sure the combination itself does not exist before the form saves.

Any help would be greatly appreciated!


Solution

  • Use a sfValidatorCallback. In your form class, add the following in the setup() function:

    $this->validatorSchema->setPostValidator(new sfValidatorCallback(array('callback' => array($this, 'YOURCALLBACKFUNCTIONNAME'))));
    

    Then, you can create this in the same file, the call back function:

    public function YOURCALLBACKFUNCTIONNAME($validator, $values) {
       //Validate form here
       //Access form items using  $values['FORMNAME'];
       //$error = new sfValidatorError($validator, 'A Error Message.');
       //$es = new sfValidatorErrorSchema($validator, array('FORMITEM' => $error);
       //throw $es;
       }