Doctrine Test 2

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

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

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

An object

 /** * @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:

  • I do not know in which column?
  • I do not want to check the unique manually

If I skip validate () from the entity, then unique (from this error.log) will be found

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

but, for example, the user saves 2 records, and the first is erroneous, and the second is valid, after the first save, the EntityManager closes, and I can’t save the second (good) record because the "EntityManager is closed".

What is the best solution for this problem?

+6
source share
2 answers

There are several ways to do validation in D2: - business logic associated with a single object, as you described in your post - listener-based validation, validation http://www.doctrine-project.org/docs/orm/2.0/en /reference/events.html#preupdate , ValidCreditCardListener example - third-party library check, something similar is described here: Zend_Validate_Db_RecordExists with Doctrine 2? and Zend_Validate: Db_NoRecordExists with doctrine. If you use a specific structure to render forms, you can integrate validation into it.

I used entity validation for business logic related to a single object:

 /** * @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 confirmation to force some rules, such as uniqueness, because in my applications entities can be created not only on the basis of forms.

+3
source

Remember to specify @HasLifecycleCallbacks in essence.

 /** * @Entity @Table(name="songs") @HasLifecycleCallbacks */ class Song { ... /** @PrePersist @PreUpdate */ public function doStuffOnPreUpdatePrePersists() { ... } } 
+2
source

Source: https://habr.com/ru/post/888708/


All Articles