Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 附加用户实体时用户名的Uniquentity不起作用_Php_Symfony - Fatal编程技术网

Php 附加用户实体时用户名的Uniquentity不起作用

Php 附加用户实体时用户名的Uniquentity不起作用,php,symfony,Php,Symfony,我有一个公司实体的表单,我想在这里为这个公司创建一个管理员用户。 在这个表单中,当创建相同的用户名时,我需要处理重复的条目 Uniquentity可以在单独的用户表单上创建用户,但不能在公司表单上工作 User.php ... use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity(repositoryClass="App\Repository\UserRepository&

我有一个公司实体的表单,我想在这里为这个公司创建一个管理员用户。 在这个表单中,当创建相同的用户名时,我需要处理重复的条目

Uniquentity可以在单独的用户表单上创建用户,但不能在公司表单上工作

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;
    
    ...

}
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,
        ]);
    }
}
  /**
     * @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(),
        ]);
    }
CompanyType.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;
    
    ...

}
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,
        ]);
    }
}
  /**
     * @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(),
        ]);
    }
CompanyController.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;
    
    ...

}
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,
        ]);
    }
}
  /**
     * @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(),
        ]);
    }
我如何处理这个问题?

根据我的经验,我用以下方式解决了我的问题:

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' => '',
            'company' => $company,
            'form' => $form->createView(),
            'errors' => '',
        ]);
    }
基于此,我通过以下方式解决了我的问题:

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' => '',
            'company' => $company,
            'form' => $form->createView(),
            'errors' => '',
        ]);
    }