UniqueEntity doesn't work

Viewed 2251

@UniqueEntity doesn't work for me. In controller I use $form->isValid() and form passes, but it shouldn't. Instead my own defined message, I got MySQL error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'media30' for key 'UNIQ_115E494BF47645AE'

I have following forms:

    class BIPType extends AbstractType{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name');
        $builder->add('url');
    }

    public function getDefaultOptions(array $options)
    {
        return array(
            'data_class' => 'AppBundle\Entity\Bip',
        );
    }
}

and next, overwritten FOSUser UserType form for registration which include BIPType:

class UserType extends AbstractType{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $biptype = new BIPType();
        $builder
            ->add('bip', $biptype, array(
            'data_class'=>'AppBundle\Entity\Bip'))
            ->add('nazwisko')
            ->add('imie')
            ;
    }

    public function getParent()
    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
        // Or for Symfony < 2.8
        // return 'fos_user_registration';
    }

    public function getBlockPrefix()
    {
        return 'app_user_registration';
    }

    // For Symfony 2.x
    public function getName()
    {
        return $this->getBlockPrefix();
    }
}

and BIP entity

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


/**
 * @ORM\Entity
 * @UniqueEntity(fields="url", message="URL is already in use")
 * @ORM\Table(name="bips")
 */
class Bip
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(name="url", type="string", unique=true)
     */
    protected $url;

    /**
     * @ORM\Column(type="string")
     * @Assert\Length(
     *      min = "3",
     *      max = "25",
     *      minMessage = "Nazwa BIPu musi mieć conajmniej 3 znaki.",
     *      maxMessage = "Nazwa BIPu może mieć conajwyżej 25 znaki."
     *)
     */
    protected $name;


    /**
     * @Assert\Image(
     *     minWidth = 80,
     *     maxWidth = 200,
     *     minHeight = 80,
     *     maxHeight = 200
     * )
     */
    protected $file;

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    private $temp;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $path;

    /**
     * @ORM\Column(type="boolean", nullable=false)
     */
    private $public;
2 Answers
Related