附加用户实体时,用户名的UniqueEntity不起作用

问题描述

我有公司实体的表单,我还想在该表单中为该公司创建管理员用户在这种形式下,当创建相同的用户名时,我需要处理重复的条目。

UniqueEntity在创建用户的单独用户表单上工作正常,但在公司表单上工作不正常。

User.PHP

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

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @ORM\Table(name="`user`")
 * @UniqueEntity("username",message="This username is already in use.")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string",length=180,unique=true)
     */
    private $username;


    /**
     * @ORM\ManyToOne(targetEntity=Company::class,inversedBy="users")
     */
    private $company;
    
    ...

}

CompanyType.PHP

namespace App\Form;

use App\Entity\Company;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class CompanyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder,array $options)
    {
        $builder
            ->add('name',TextType::class,array(
                'label' => 'Company name'
                )
            ))
            ->add('user',AccountType::class,array(
                'label' => 'Company admin','mapped' => false,'data_class' => AccountType::class,))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Company::class,]);
    }
}

CompanyController.PHP

  /**
     * @Route("/new",name="company_new",methods={"GET","POST"})
     */
    public function new(Request $request,UserPasswordEncoderInterface $encoder): Response
    {
        $company = new Company();
        $form = $this->createForm(CompanyType::class,$company);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();

            $user = new User();
            $user->setUsername($form['user']['username']->getData())
                ->setPassword($encoder->encodePassword($user,$form['user']['password']->getData()))
                ->setRoles(array('ROLE_COMPANY_ADMIN'));
            $entityManager->persist($user);

            $company->addUser($user);
            $entityManager->persist($company);
            $entityManager->flush();

            return $this->redirectToRoute('company_index');
        }

        return $this->render('company/new.html.twig',[
            'username' => '','company' => $company,'form' => $form->createView(),]);
    }

如何处理此问题?

解决方法

基于Documentation,我通过以下方式解决了我的问题:

ComapnyController.php

public function new(Request $request,UserPasswordEncoderInterface $encoder,ValidatorInterface $validator): Response
    {
        $company = new Company();
        $form = $this->createForm(CompanyType::class,$company);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();

            $user = new User();
            $user->setUsername($form['user']['username']->getData())
                ->setPassword($encoder->encodePassword($user,$form['user']['password']->getData()))
                ->setRoles(array('ROLE_COMPANY_ADMIN'));

            $errors = $validator->validate($user);

            if (count($errors) > 0) {
                return $this->render('company/new.html.twig',[
                    'username' => $form['user']['username']->getData(),'company' => $company,'form' => $form->createView(),'errors' => $errors,]);
            }

            $entityManager->persist($user);

            $company->addUser($user);
            $entityManager->persist($company);
            $entityManager->flush();

            return $this->redirectToRoute('company_index');
        }

        return $this->render('company/new.html.twig',[
            'username' => '','errors' => '',]);
    }