Symfony 3.4 - 在更新到db之前检查唯一字段

时间:2018-04-20 21:02:06

标签: symfony symfony-3.4

我对symfony有点新鲜。 试图创造一些东西!不确定atm是什么,有点练习。

我正在创建一个"用户登录系统" (尝试), 用户能够: - 注册, - 登录, - 更新用户帐户。

每个注册用户都有一个我从用户名(唯一)生成的唯一slug。 但我希望用户提供更新用户名的选项,如果没有采用。 在使用doctrine :(重复条目)

的错误测试itt响应时

问题: 有没有办法检查在更新发生之前是否已经使用了用户名? 什么是管理用户的最佳实践?

我不是第三方捆绑包的粉丝,如:FOSUserBundle。 我喜欢自己创作。

看看我的控制器 所有的魔法都发生在editAction()

<?php

namespace Project\UrtBundle\Controller;

use Project\UrtBundle\Entity\UrtUsers;
use Project\UrtBundle\Helpers\UrtHelper;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * UrtUser controller.
 *
 * @Route("admin/users")
 */
class UrtUsersController extends Controller
{

    /**
     * Lists all user entities.
     *
     * @Route("/", name="admin_users_index")
     * @Method("GET")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $users = $em->getRepository('ProjectUrtBundle:UrtUsers')->findAll();

        return $this->render('ProjectUrtBundle:users:index.html.twig', array(
            'users' => $users
        ));
    }

    /**
     * Creates a new user entity.
     *
     * @Route("/new", name="admin_users_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request, UserPasswordEncoderInterface $encoder, UrtHelper $urthelper)
    {
        $user = new UrtUsers();
        $form = $this->createForm('Project\UrtBundle\Form\UrtUsersType', $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // password Bcrypt
            $password = $user->getPassword();
            $encoded = $encoder->encodePassword($user, $password);
            $user->setPassword($encoded);

            // slug
            $username = $user->getUsername();
            $slug = $urthelper->slugify($username);
            $user->setSlug($slug);


            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            return $this->redirectToRoute('admin_users_show', array('id' => $user->getId()));
        }

        return $this->render('ProjectUrtBundle:users:new.html.twig', array(
            'user' => $user,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a user entity.
     *
     * @Route("/{id}", name="admin_users_show")
     * @Method("GET")
     */
    public function showAction(UrtUsers $user)
    {
        $deleteForm = $this->createDeleteForm($user);

        return $this->render('ProjectUrtBundle:users:show.html.twig', array(
            'user' => $user,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing user entity.
     *
     * @Route("/{id}/edit", name="admin_users_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, UrtUsers $user, UserPasswordEncoderInterface $encoder, ValidatorInterface $validator)
    {
        $deleteForm = $this->createDeleteForm($user);
        $editForm = $this->createForm('Project\UrtBundle\Form\UrtUsersEditType', $user);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {

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

            //dump($errors); die;

            $password = $user->getPassword();
            $encoded = $encoder->encodePassword($user, $password);
            $user->setPassword($encoded);

            $updateTime = new \DateTime();
            $user->setUpdatedAt($updateTime);

            $em = $this->getDoctrine()->getManager();

            if (count($errors) > 0) {
                /*
                 * Uses a __toString method on the $errors variable which is a
                 * ConstraintViolationList object. This gives us a nice string
                 * for debugging.
                 */
                //$errorsString = (string) $errors;

                return $this->render('ProjectUrtBundle:users:edit.html.twig', array(
                    'user' => $user,
                    'erros' => $errors,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                ));
            }

            $em->persist($user);
            dump($em); die;
            $em->flush();

            return $this->redirectToRoute('admin_users_index', array('id' => $user->getId()));
        }

        return $this->render('ProjectUrtBundle:users:edit.html.twig', array(
            'user' => $user,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a user entity.
     *
     * @Route("/{id}", name="admin_users_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, UrtUsers $user)
    {
        $form = $this->createDeleteForm($user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($user);
            $em->flush();
        }

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

    /**
     * Creates a form to delete a user entity.
     *
     * @param UrtUsers $user The user entity
     *
     * @return \Symfony\Component\Form\FormInterface
     */
    private function createDeleteForm(UrtUsers $user)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_users_delete', array('id' => $user->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}

2 个答案:

答案 0 :(得分:1)

尝试为该特定字段添加UniqueEntity

/**
     * UrtUsers
     *
     * @ORM\Table(name="UrtUsers")
     * @UniqueEntity(fields={"username"}, message="Username {{ value }} already exists")
     *
     */
    class UrtUsers
    {

    }

答案 1 :(得分:0)

在尝试将新用户名插入数据库之前,您应该查询数据库以查看用户名是否存在。