Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UniqueConstraint error message handling in Symfony2

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'))
    ;
}
like image 489
BentCoder Avatar asked Dec 08 '25 20:12

BentCoder


1 Answers

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.

like image 105
bzeaman Avatar answered Dec 11 '25 10:12

bzeaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!