6

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?

Robertoq
  • 373
  • 1
  • 5
  • 11

2 Answers2

3

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.

Community
  • 1
  • 1
WizardZ
  • 1,372
  • 13
  • 12
2

Remember to define @HasLifecycleCallbacks in the entity.

/**
 * @Entity @Table(name="songs") @HasLifecycleCallbacks
 */
class Song
{
   ...
   /** @PrePersist @PreUpdate */
    public function doStuffOnPreUpdatePrePersists()
    {
      ...
    }
}
animuson
  • 53,861
  • 28
  • 137
  • 147
Joan
  • 21
  • 2