In a project, I have an entity "customer" linked in a ManyToOne relationship to an entity "company". When a customer registers, he has to fill a form with attributes of "customer" and the name of "company"; therefore, I embedded my CompanyType in my CustomerType form.
The problem is with the validation : the name of each company should be unique and therefore I added " 'cascade_validation' => true" in CustomerType , unique=true in the entity file and the validation @UniqueEntity on the name of company. The error is well seen by doctrine, but the UniqueEntity validation doesn't work right, and the user is redirected to a 500 error page.
I tried a lot of things without any success, anyone has any idea on how to fix this ?
Here are my files :
In the Customer Entity :
/**
* @ORM\ManyToOne(targetEntity="Site\UserBundle\Entity\Company", inversedBy="customers", cascade="persist")
* @ORM\ JoinColumn(nullable=false)
*/
private $company;
In the Company entity
/**
* Company
*
* @ORM\Table()
* @ORM\Entity
* @UniqueEntity(fields={"name"}, groups={"nameCompany"})
*/
class Company
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Site\UserBundle\Entity\Customer", mappedBy="company")
*/
private $customers;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
In the Customer Form
public function buildForm (FormBuilderInterface $builder, array $options)
{
$builder->add('company', new CompanyType(), array('validation_groups' => array('nameCompany')));
}
/**
*
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions (OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'data_class' => 'Site\UserBundle\Entity\Customer',
'cascade_validation' => true,
));
}
In the Company Form :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', null,
array(
'label' => 'entity.customer.company',
'translation_domain' => 'SiteUserBundle'
));
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Site\UserBundle\Entity\Company',
'validation_groups' => array('nameCompany'),
));
}
Thanks A LOT in advance for any help !