Reputation: 77
I have an entity named Theme, its name is not the Id, but should be indexed and unique :
/**
* @Entity @Table(name="themes",
* uniqueConstraints={@UniqueConstraint(name="theme_unique",columns={"name"})},
* indexes={@Index(name="theme_idx", columns={"name"})})
*/
class Theme {...}
I create a new theme with an existing name. This delivers an error, the script stops. How should I fetch that error and continue the script?
function CreateTheme($newThemeName) {
//$theme = $this->FindByThemeName ( $newThemeName );
//if (! $theme) {
$theme = new Theme ();
$theme->setName ( $newThemeName );
$theme->setIsActive ( false );
$theme->setIsDefault ( false );
$this->entityManager->persist ( $theme );
$this->entityManager->flush ();
return $theme;
//} else {
// $this->error = "Error in flush was avoided (name not being unique)!";
// return null;
//}
Upvotes: 1
Views: 1832
Reputation: 77
That try / catch setup does not realy solve the problem :
The Doctrine\ORM\EntityManager is closed due to the SQL error. The EntityManager cannot simply be reset (or reopened). Link about this subject :
Statement : "The best is to avoid getting a closed entity manager (which means validating your data before sending them to the database)"
Conclusion : The annotation that sets UniqueConstraints is useless : It does not prevent the execution of a syntax valid SQL instruction which gives the "duplicate entry" SQL error due to that constraint. This error closes the EntityManager which cannot safely be reset.... You'll need to check for vioalation of uniqueconstraints 'manually' before trying to persist and flush your new entity instance.
Upvotes: 1
Reputation: 77
Try Catch did'nt work, which is the cause of this question.
The handler for an ORMException was somehow not registered and now it is. Unclear what caused it.
function CreateTheme($themeName) {
global $entityManager;
$theme = new Theme ();
$theme->setName ( $themeName );
$theme->setIsActive ( false );
$theme->setIsDefault ( false );
try {
$entityManager->persist ( $theme );
$entityManager->flush ();
} catch (Exception $e) {
echo $e->getMessage();
$theme = null;
}
return $theme;
}
Gives, when a duplicate name is used :
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test' for key 'theme_unique'
Upvotes: 0