How do I attach a message to uniqueConstraints below in the entity itself? Second query below will generate An exception occurred while executing....SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry.... Instead of this unfriendly message how can I print "You request whatever whatever ..."?
SQL 1- INSERT INTO cars (model, brands_id) VALUES ('bmw', '5')
SQL 2- INSERT INTO cars (model, brands_id) VALUES ('bmw', '5')
Note: I find Symfony documentation poor in general and the most seem to be short-cut. If you're looking for a solution and if someone knows the answer then you're luck if not you're ....
ENTITY
/**
* @ORM\Entity
* @ORM\Table(name="cars", uniqueConstraints={@ORM\UniqueConstraint(columns={"model", "brands_id"})})
*/
class Cars
{
CONTROLLER
try
{
$submission = $form->getData();
$em = $this->getDoctrine()->getManager();
$cars = new Cars();
$cars->setModel($submission->getModel());
$cars->setBrands($submission->getBrands());
$em->persist($cars);
$em->flush();
.......
}
catch (Exception $e)
{
......
}
FORM TYPE
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->setAction($options['action'])
->setMethod('POST')
->add('brands', 'entity',
array(
'class' => 'CarBrandBundle:Brands',
'property' => 'name',
'multiple' => false,
'expanded' => false,
'empty_value' => '',
'query_builder' => function (EntityRepository $repo)
{
return $repo->createQueryBuilder('b')->orderBy('b.name', 'ASC');
}
))
->add('model', 'text', array('label' => 'Model'))
->add('button', 'submit', array('label' => 'Submit'))
;
}
Put a validation.yml file in your src/Car/BrandBundle/Resources/config folder.
The contents should be similar to this:
CAR\BrandBundle\Entity\Cars:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
fields: [model, brands_id]
message: "your_message_here"
You could also use annotations to use validation constraints.
For more info read the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With