Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 validation

I have a problem with validation. In Doctrine 1 i used this:

if ($model->isValid()) {
    $model->save();
} else {
    $errorStack = $model->getErrorStack();
    ...
}

and in $errorStack i got the column name and the error message. But in Doctrine 2 I can use just it:

Entity

/**
 * @PrePersist @PreUpdate
 */
public function validate()
{
    if ($this->name == null)) {
        throw new \Exception("Name can't be null"); 
    }
}

Controller:

try {
    $user = new \User();
    //$user->setName('name');
    $user->setCity('London');
    $this->_entityManager->persist($user); 
    $this->_entityManager->flush();
} catch(Exception $e) {
    error_log($e->getMessage());
} 

but I have two problems whit it:

  • i don't know which column?
  • i don't want to check unique manually

If i skip validate() from entity the unique will be catched (from this error.log)

Unique violation: 7 ERROR:  duplicate key value violates unique constraint "person_email_uniq"

but for example the user save 2 records and the first is wrong, but the second valid, after the first save the EntityManager will close and I can't save the second(good) record because of "The EntityManager is closed".

Which is the best solution for this problem?

like image 622
Robertoq Avatar asked May 21 '11 15:05

Robertoq


1 Answers

There are few ways to do validation in D2: - business logic related to one entity as you described in your post - validation based on listeners, check http://www.doctrine-project.org/docs/orm/2.0/en/reference/events.html#preupdate, ValidCreditCardListener example - validation based on third party libraries, something similar described here: Zend_Validate_Db_RecordExists with Doctrine 2? and Zend_Validate: Db_NoRecordExists with Doctrine If you use a particular framework for form rendering you can integrate validation into it.

I used validation in entities for business logic related to one entity:

/**
 * @PrePersist @PreUpdate
 */
public function validate()
{
    $this->errors = array();
    if ($this->name == null)) {
        $this->errors['name'][] = 'Something wrong'; 
    }
    if (0 < count($errors)) {
        throw new Exception('There are errors');
    }
}

public function getErrors()
{
   return $this->errors;
}

and listeners validation to force some rules such as uniqueness because in my application entities can be created not only based on forms.

like image 101
WizardZ Avatar answered Sep 23 '22 12:09

WizardZ