Symfony - 唯一的实体约束不起作用

时间:2017-10-18 16:29:34

标签: php forms symfony constraints unique

我目前正在开发Symfony v3.3.6项目。 我有一个用户创建表单。 我想确保电子邮件和用户名(fos用户包)是唯一的。

我目前拥有这个模型(只是一小部分):

<?php

namespace ProjectBundle\Entity\User;

use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\SoftDeleteable\Traits\SoftDeleteableEntity;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use ProjectBundle\Entity\Gender\Gender;
use ProjectBundle\Entity\Organisation\Organisation;
use ProjectBundle\Entity\Traits\BlameableEntity;
use ProjectBundle\Entity\User\Profile;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator;


/**
 * @ORM\Entity(repositoryClass="ProjectBundle\Repository\User\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @ORM\Entity
 * @UniqueEntity(fields={"email"}, groups={"registration"})
 * @UniqueEntity(fields={"username"}, groups={"registration"})
 * @ORM\Table(name="user")
 */
class User extends BaseUser implements AdvancedUserInterface, \Serializable
{
    use TimestampableEntity;
    use SoftDeleteableEntity;
    use BlameableEntity;

    const ID_ORGA_GC = 1;

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;


    /**
     * @Assert\NotBlank()
     */
    protected $username;

    /**
     * @Assert\NotBlank(groups={"registration"})
     * @Assert\Length(groups={"registration"},
     *      min = 2,
     *      max = 254,
     *      minMessage = "Votre mot de passe doit comporter au minimum {{ limit }} caractères.",
     *      maxMessage = "Votre mot de passe doit comporter au maximum {{ limit }} caractères."
     * )
     *
     * @var string
     */
    protected $plainPassword;


    /**
     * @Assert\NotBlank()
     * @Assert\Email(
     *     message = "L'adresse mail '{{ value }}' n'est pas valide.",
     *     checkMX = true
     * )
     *
     * @var string
     */
    protected $email;

正如您所看到的,我为用户名和电子邮件添加了2个“唯一实体”属性,并在每个属性上添加了“NotBlank”约束。

在我的控制器中,我打电话给我的表格:

$form = $this->createForm('ProjectBundle\Form\User\UserType', $entity,array('organisation' => $organisations, 'validation_groups' => array('Default','registration')));

$form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {

但是,即使我写了一个已存在的电子邮件地址,我也会遇到这种情况,当时间到了刷新时,我会遇到一个很大的SQL错误:

SQLSTATE [23000]: Integrity constraint violation: 1062 Duplicate entry 'emailtest@test.fr' for key 'UNIQ_8D93D649A0D96FBF'

但有趣的评论是'NotBlank'约束正常工作,并在我的视图中显示'值不能为空'

这是我的表格:

class UserType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('lastname',null,array('required' => true))
            ->add('firstname')
            ->add('gender',null,array('required'=>true))
            ->add('organisationMember',null,array(
                'required' => true,
                'choices' => $options['organisation'],
                'group_by' => 'type_organisation',
                'placeholder' => 'Choisissez votre organisation'
            ))
            ->add('job')
            ->add('lang', null, array(
                'required' => true
            ))
            ->add('mobile',null, array(
                'required' => false
            ))
            ->add('phone', null, array(
                'required' => true
            ))
            ->add('enabled')
            ->add('is_external')
            ->add('alert_failure')
            ->add('alert_full')
            ->add('alert_other')
            ->add('plainPassword', TextType::class, array('required' => false))
            ->add('email')
            ->add('profile', null, array(
                'required' => true,
                'placeholder' => 'Choose an organisation !',
            ));
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'ProjectBundle\Entity\User\User',
            'organisation' => 'ProjectBundle\Entity\Organisation\Organisation',
            'profiles' => 'ProjectBundle\Entity\User\Profile',
            'csrf' => true,
        ));

    }
}

如果有人有解决方案。

提前谢谢!

2 个答案:

答案 0 :(得分:0)

你试过这样的事吗:

/**
 * @ORM\Entity(repositoryClass="ProjectBundle\Repository\User\UserRepository")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @ORM\Entity
 * @UniqueEntity(fields={"email", "username"}, groups={"registration"})
 * @ORM\Table(name="user")
 */

但请确保您拥有电子邮件和用户名的唯一索引。

答案 1 :(得分:0)

目前,@ CarcaBot的响应仅适用于DEV,更新不会在PROD中更改我的问题,而文件是相同的,以及数据库。

一个想法?