Lauren
Lauren

Reputation: 71

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!

Upvotes: 2

Views: 3159

Answers (3)

Faraona
Faraona

Reputation: 1700

I know that your question is about doctrine but for those who is looking for this answer and use Proepl, there is Propel validator for this:

Another useful Model-related validator is the sfValidatorPropelUnique validator, which checks that a new value entered via a form doesn't conflict with an existing value in a database column with a unique index. For instance, two users cannot have the same login, so when editing a User object with a form, you must add a sfValidatorPropelUnique validator on this column:

// Propel unique validator $form->setValidator('nickname', new sfValidatorPropelUnique( array( 'model' => 'User', 'column' => 'login' )));

Upvotes: 0

Jeremy Kauffman
Jeremy Kauffman

Reputation: 10403

There is actually a Doctrine validator specifically for this, sfValidatorDoctrineUnique. In your form, try:

public function configure()
{
  parent::configure();
  $this->mergePostValidator(new sfValidatorDoctrineUnique(array(
      'model' => 'MyModelName',
      'column' => array('name')
  )));
  $this->mergePostValidator(new sfValidatorDoctrineUnique(array(
      'model' => 'MyModelName',
      'column' => array('parent1', 'parent2', 'parent3', 'parent4', 'parent5')
  )));
}

Upvotes: 2

jgallant
jgallant

Reputation: 11273

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;
   }

Upvotes: 4

Related Questions