Symfony2 validation exception with unique constraint - validation

I have an entity "Movie" which has a unique constraint through doctrine annotation. Based on the movie entity I have auto generated a CRUD layer. When I now try to add a new movie I get the following exception:
Only field names mapped by Doctrine can be validated for uniqueness.
When the constraint is removed everything works fine. Do somebody has an idea where the problem lays and how I can resolve it?
My guessing is the entity, because it is new, is not sync with the EntityManager and therefore could not check the constraint. Am I'close?
I'm using Symfony 2.0.1 with Doctrine 2.1.1, MySQL as Database.
Thanks,
-lony
The "Movie" Entity:
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="type", type="string")
* #ORM\DiscriminatorMap({"movie" = "Movie", "series" = "Series"})
*
* #DoctrineAssert\UniqueEntity("title_orginal")
*/
class Movie {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $titleOrginal
*
* #ORM\Column(name="title_orginal", type="string", length=255, unique="true")
*/
private $titleOrginal;
..

Your syntax is wrong.
Use this:
#DoctrineAssert\UniqueEntity(fields={"title_orginal"})
instead of
#DoctrineAssert\UniqueEntity("title_orginal")
You can then customize the violation message like this :
#DoctrineAssert\UniqueEntity(fields={"title_orginal", message="my.custom.message"})
and translate this message by using a validators.xliff file (it must be named like that).
I tell you this because I struggled the other day with it and was obliged to debug to find about this validators.xliff naming convention.

I think there is a small typo:
#DoctrineAssert\UniqueEntity(fields={"title_orginal", message="my.custom.message"})
should be:
#DoctrineAssert\UniqueEntity(fields={"title_orginal"}, message="my.custom.message")
and for several fields
#DoctrineAssert\UniqueEntity(fields={"title_orginal", "field2"}, message="my.custom.message")

Related

Symfony 5 - Doctrine - Index not created in custom ManyToOne relation

I've created two Entity, and i try to create a custom relation between them, without using the default syntax.
See :
/**
* #ORM\Entity(repositoryClass=LandRepository::class)
* #ORM\HasLifecycleCallbacks()
*/
class Land
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $libelle;
/**
* #ORM\Column(type="integer")
*/
private $uid;
/**
* #ORM\OneToMany(targetEntity=Ride::class, mappedBy="uidparent")
*/
private $rides;
}
/**
* #ORM\Entity(repositoryClass=RideRepository::class)
* #ORM\HasLifecycleCallbacks()
*/
class Ride
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $libelle;
/**
* #ORM\ManyToOne(targetEntity=Land::class, inversedBy="rides")
* #ORM\JoinColumn(name="uidparent", referencedColumnName="uid")
*/
private $uidparent;
}
Tables are correctly created, but the last instruction have an error.
In MySQL, i made some test, and i need to create an index on "uid" column in "land" table.
So, i changed the header of my class "Land" to force the index
/**
* #ORM\Entity(repositoryClass=LandRepository::class)
* #ORM\Table(name="land",indexes={#ORM\Index(columns={"uid"})})
* #ORM\HasLifecycleCallbacks()
*/
class Land
{
/ ... /
}
I don't understand why i need to specify this index creation.
I hope to have something like this :
(PS : I know i can use the classic syntax (using in my entity Ride a column auto named "land_id") but I want to understand and master this alternative syntax to manage future complex entities and associations)
Thanks !
Need to manually specify in Entity header annotation :
#ORM\Table(name="land",indexes={#ORM\Index(columns={"uid"})})

symfony - unique entity constraint with not mapped field

my goal is to validate an entity with a uniqueEntity constrainte on a field. This field is composed of 2 not mapped fields concatenated using a lifecycle callback PrePersist. The problem is that the validation does not occur and the system allows me to insert data into the database when it should not.
/**
* Recipe
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\RecipeRepository")
* #ORM\HasLifecycleCallbacks()
* #UniqueEntity(
* ignoreNull = false,
* fields={"amount"},
* message="Not valid"
* )
*/
class Recipe
{...}
...
/**
* #ORM\PrePersist()
*/
public function preSave()
{
$this->amount = $this->getAmountInteger() . '.' . $this->getAmountDecimal();
}
i have a entity with this definition and run fine, but your case is different because your set 'amount' in the preSave...
* #UniqueEntity(fields={"amount"}, message="Not valid")
* #ORM\Table(uniqueConstraints={#ORM\UniqueConstraint(name="unique_amount", columns={"amount"})})
And in the other entity i used
#ORM\Column(type="string", length=127, nullable=false, unique=TRUE)
The different is in the first case i use compuest key and define key in the fields={field1,field2}.. in the second example i use simple unique key.

Many-to-Many Relations using non-"id" Primary Key in Doctrine

So I'd like to create two entities and make a many-to-many reference. I would love to make this association using a string primary key on one table. This seems to be really hard, at least it took me pretty much time trying without any results yet.
This is my approach:
First entity:
namespace Project\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="User")
*/
class User
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $Id;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="Users")
* #ORM\JoinTable(name="role_user",
* joinColumns={#ORM\JoinColumn(name="User_Id", referencedColumnName="Id")},
* inverseJoinColumns={#ORM\JoinColumn(name="Role_Name", referencedColumnName="Name")}
* )
*/
private $Roles;
}
And the second:
namespace Project\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="Role")
*/
class Role
{
/**
* #ORM\Id
* #ORM\Column(type="string", length=256)
*/
private $Name;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="Roles")
* #ORM\JoinTable(name="role_user",
* joinColumns={#ORM\JoinColumn(name="Role_Name", referencedColumnName="Name")},
* inverseJoinColumns={#ORM\JoinColumn(name="User_Id", referencedColumnName="Id")}
* )
*/
private $Users;
}
Output of ./app/console doctrine:schema:validate:
[Mapping] FAIL - The entity-class 'Project\AdminBundle\Entity\User' mapping is invalid:
* The referenced column name 'Id' has to be a primary key column on the target entity class 'Project\AdminBundle\Entity\User'.
* The referenced column name 'Id' has to be a primary key column on the target entity class 'Project\AdminBundle\Entity\Role'.
What do I miss?
Attention upper/lowercase! Doctrine generates its columns as lowercase per default. This solves the issue:
* joinColumns={#ORM\JoinColumn(name="User_Id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="Role_Name", referencedColumnName="name")}
This it over-complicated; it's enough to put this into the Role entity:
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="Roles")
* #ORM\JoinColumn(name="role_user", referencedColumnName="name")
*/
private $Users;
I only thought about this when writing the question.. what a good method to think about the problem again from scratch.
Cheers

Symfony2 - UniqueEntity no action

I have an entity named Test with two fields: id and name.
I would like to have the name as unique.
What I did:
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
...
/**
* Company\AppBundle\Entity\Test
*
* #ORM\Table(name="test")
* #UniqueEntity("name")
* #ORM\Entity(repositoryClass="Company\AppBundle\Entity\TestRepository")
*
*/
class Test
{
....
/**
* #var string$name
*
* #ORM\Column(name="name", type="string", length=200, nullable=false, unique=true)
*/
private $name;
....
In my controller, I am using:
if ($form->isValid()) {
....
But the validation goes through. Am I missing something?
The unique annotation is for doctrine, it passes it to the database level and the error gets thrown from there. It will not know that the entity exists until you try to save it. To do the checks in php you have to query for the unique attribute yourself and check if it exists...

No relations updated in the DB after writing symfony/doctrine associations

So I am working on a project in symfony 3.0.1. I have generated entities (via doctrine:generate:entity with the following interactive setup questions) and then did the doctrine:schema:update --force to generate the tables in the DB from the Doctrine entities.
I then went in the entities and created associations.
After that I went ahead and did another doctrine:schema:update -- force and after checking in phpMyAdmin no relations were created by the schema update I forced.
Is there something else I am missing? See below my entities:
namespace MyAppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Logins
*
* #ORM\Table(name="logins")
* #ORM\Entity(repositoryClass="MyAppBundle\Repository\LoginsRepository")
*/
class Logins
{
/**
* #var int
*
* #ORM\Column(name="RoleID", type="integer")
* #ORM\ManyToOne(targetEntity="Roles", inversedBy="roleID")
* #ORM\JoinColumn(name="roleID", referencedColumnName="roleID")
*/
private $roleID;
'
'namespace MyAppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Roles
*
* #ORM\Table(name="roles")
* #ORM\Entity(repositoryClass="MyAppBundle\Repository\RolesRepository")
*/
class Roles
{
/**
* #var int
*
* #ORM\Column(name="roleID", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\OneToMany(targetEntity="Logins", mappedBy="roleID")
*/
private $roleID;
public function __construct() {
$this->roleID=new ArrayCollection();
Still not sure why there were conflicts, but I resolved my problem with Doctrine reverse engineering. I created the relations in PMA and then generated mapping from it. All worked out well.
EDIT: The guy in comments to my post was right. I cannot assign One-to-Many on an Identity property.
I have had frustrating problems with relations not updating on my production environment several times now. My code would execute as expected with no errors, but the table(s) simply wouldn't update.
I've discovered that if you are using APC and you have just added a new relationship, you need to restart the web server in order for old versions of the entity classes to be flushed out.

Resources