简体   繁体   中英

How should I handle Symfony2/Doctrine exceptions

Maybe this is a hot topic and some others talk about this but I don't find a good solution yet to this problem. Take this error for UNIQUE fields as example. When I try to insert the same values to the database I get this error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'j1234567' for key 'UNIQ_FC3A5A1592FC23A8'

Of course this happens on app_dev.php (development) enviroment but I don't know how to deal with this in order to show an error page to users instead of this ugly error. I test the same code at production then the ugly error disappear but I get this instead:

ERROR: INTERNAL SERVER ERROR

Paths, I though, are more than one, for example I could check the existence of the record before I insert or before I send the request trough AJAX but I want to learn how to achieve this by using Symfony2 and Doctrine2 asserts. I have already added this code to my entities:

<?php

....
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * SysPerfil
 *
 * @ORM\Entity
 * @ORM\Table(name="sys_perfil")
 * @UniqueEntity(fields={"rif"}, message="Este RIF ya existe en nuestra base de datos")
 * @UniqueEntity(fields={"ci"}, message="Este CI ya existe en nuestra base de datos")
 * @UniqueEntity(fields={"nombre"}, message="Este nombre ya existe en nuestra base de datos")
 */
class SysPerfil
{
    ....

But it's not working since I get the error mentioned above, so what is the best way to handle this? Any ideas? Advices? Docs?

Add form types

Yes, I send the data trough a form type, see below:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);
    $builder
            ->add('email', 'email', array(
                'required' => true,
                'label' => 'Email',
                'trim' => true
            ))
            ->add('password', 'password', array(
                'required' => true,
                'label' => 'Contraseña',
                'always_empty' => true
            ))
            ->add('confirm', 'password', array(
                'required' => true,
                'mapped' => false,
                'label' => 'Verificar contraseña',
                'always_empty' => true
            ))
            ->add('enabled', 'checkbox', array(
                'required' => true,
                'label' => 'Activo?',
                'data' => true
            ))
            ->add('perfil', new AdminPerfilType());
}

And AdminPerfilType.php :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    parent::buildForm($builder, $options);
    $builder
            ->add('persJuridica', 'choice', array(
                'choices' => RifType::getChoices(),
                'required' => true,
                'label' => 'RIF',
                'trim' => true,
                'attr' => array(
                    'class' => 'persJuridica'
                )
            ))
            ->add('roleType', 'choice', array(
                'choices' => AdminRoleType::getChoices(),
                'required' => true,
                'label' => "Tipo de Usuario",
                'trim' => true
            ))
            ->add('rif', 'text', array(
                'required' => true,
                'label' => false,
                'trim' => true,
                'attr' => array(
                    'class' => "numeric",
                    'maxlength' => 15
                )
            ))
            ->add('ci', 'text', array(
                'label' => 'CI',
                'trim' => true,
                'attr' => array(
                    'class' => "numeric ci",
                    'disabled' => 'disabled'
                )
            ))
            ->add('nombre', 'text', array(
                'required' => true,
                'label' => 'Nombre',
                'trim' => true
            ))
            ->add('apellido', 'text', array(
                'required' => true,
                'label' => 'Apellidos',
                'trim' => true
            ));
}

If you're looking for validation rules inside the form then I haven't since I though that Doctrine/Symfony2 handle that part already

I guess your error is because you have a Parent -> Child Entities with One-To-One mapping, your form validation is checking the parent entity validation rules without checking the child validation rules because you are not using Assert\\Valid

Example from Symfony Documentation http://symfony.com/doc/current/reference/constraints/Valid.html :

// src/Acme/HelloBundle/Entity/Address.php
namespace Acme\HelloBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Address
{
    /**
     * @Assert\NotBlank()
     */
    protected $street;

    /**
     * @Assert\NotBlank
     * @Assert\Length(max = "5")
     */
    protected $zipCode;
}

// src/Acme/HelloBundle/Entity/Author.php
namespace Acme\HelloBundle\Entity;

class Author
{
    /**
     * @Assert\NotBlank
     * @Assert\Length(min = "4")
     */
    protected $firstName;

    /**
     * @Assert\NotBlank
     */
    protected $lastName;

    //without this Symfony won't check if the inserted address is satisfying the validation rules or not 
    /**
     * @Assert\Valid
     */
    protected $address;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM