A
A
Alexander Afanasiev2019-04-11 16:15:06
symfony
Alexander Afanasiev, 2019-04-11 16:15:06

symfony. How to check if the user's login is busy?

Hello, I want to understand one question using the following code as an example. I have a controller in which the user is created:

/**
     * @Route("/users", name="user_create", methods={"POST"})
     */
    public function createUser(Request $request)
    {
        $login = $request->get('login');
        $password = $request->get('password');
        $user = new User();
        $user->setLogin($login);
        $user->setPassword($password);
        
        $entityManager = $this->getDoctrine()->getManager();    
        $entityManager->persist($user);
        $entityManager->flush();
        $user_id = $user->getId();
        return $user_id;
    }

Here User() is a standard entity.
I need to check if the given login is busy or not, and I need to check this when creating a user and when editing (the user can change the login, that's such a Wishlist). It is perfectly logical to push the check into setLogin ()
But how to do it? How to get access to the database in entity?
As I understand it, if this cannot be done by standard means without dancing with a tambourine, then I'm making shit code.
And how differently, can check in the controller? Then, when editing a user, you will have to copy-paste a piece of code ...
I would like to do something like this:
namespace App\Entity;
class User
{
     /**
     * @ORM\Column(type="string", length=100)
     */
    private $login;

    /**
     * @ORM\Column(type="string", length=100)
     */
    private $password;

    public function setLogin(string $login): self
    {
        $user = MagicGetDoctrine()->getRepository(User::class)->findByLogin($login);
        if ($user) {
            if ($this->id != $user->getId()) {
                throw new Exceptions\UserLoginIsBusyException();
            }
        }
        $this->login = $login;
        return $this;
    }
}

How would you do this check?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
user49981, 2019-04-11
@XanderEVG

https://symfony.com/doc/current/bundles/FOSUserBun...
https://stackoverflow.com/a/51770985/10111639

use FOS\UserBundle\Model\User as FosUser;

class User extends FosUser
{

}

If that's not enough:
https://symfony.com/doc/current/reference/constrai...
https://symfony.com/doc/current/validation/transla...

I
iAdil, 2019-04-11
@iAdil

Just add Unique

/**
 * @ORM\Entity
 * @UniqueEntity("login")
 */
class User
{

For the future, if you need not just uniqueness, but some other condition to use, create Validation Constraints

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question