I’m having trouble validating the “uniqueness” of two fields, being one of them an entity of an association. The logic is that there can’t be two taxes with the same description for a single country.
Here’s my (failed) attempt:
/**
* @ORM\Entity
* @ORM\Table(name="taxes", uniqueConstraints={@ORM\UniqueConstraint(columns={"country_id", "description"})})
* @UniqueEntity(fields={"country", "description"})
*/
class Tax
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column()
*/
protected $description;
/**
* @ORM\Column(type="float")
*/
protected $value;
/**
* @ORM\ManyToOne(targetEntity="Country", inversedBy="taxes")
*/
protected $country;
//getters and setters...
}
When I test my app with a duplicate tax entity, the form pass the validation (when it shouldn’t) and Symfony throws an error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1-ITBMS' for key 'country_id'
UPDATE: I found that this is a known bug in Doctrine 2.1 that is fixed in Doctrine 2.2. Unfortunately, Symfony 2.0.11 (my current version) ships with Doctrine 2.1 and I don’t know how to update my deps file appropriately
UPDATE 2: After updating my deps and deps.lock files to get the latest Doctrine 2.2.1 files as @elnur suggested below, the problem is still there: The composite unique key is created in the database but the validation is not correctly performed. Upgrading the Doctrine files alone is not solving the problem.
UPDATE 3: I even updated Symfony core to version 2.0.12 but it doesn’t solve the problem either.
UPDATE 4 (SOLVED): I found the error inside my controller. Here is my original controller code:
public function createAction($country_id)
{
//...
if($request->getMethod() == 'POST')
{
$form->bindRequest($request);
$tax->setCountry($country); //HERE IS THE ERROR...
if($form->isValid())
{
//...
}
}
//...
}
Setting the country before binding the request was the solution.
public function createAction($country_id)
{
//...
if($request->getMethod() == 'POST')
{
$tax->setCountry($country); //NOW IT WORKS...
$form->bindRequest($request);
if($form->isValid())
{
//...
}
}
//...
}
To upgrade to Doctrine 2.2.1, replace related entries in your
depsfile with these:And in your
deps.lockwith these:Then run:
UPDATE
Since upgrading Doctrine didn’t work, try the
UniqueEntityCaseInsensitiveconstraint from myValidatorBundle.Install the bundle, import the constraint:
and replace your
with