symfony - symfony2 FOSUserBundle generate alphanumeric username -
in symfony project have different types of users: 2 admin accounts ids 1 , 2 , username can 100 account company ids of 3-102 , username must aa001 aa100 , accounts ordinary users username aa101, aa102, ...
the 2 admin accounts , accounts of company create symfony command generate them.
my question how generate user name others use registration form first register username aa101 , on
my first idea : recover id max (maxid) , use ($username = 'aa'.maxid-1) happens if 2 users register @ same time
second idea : persist entity , id (afterpersist events) , use ($username = 'aa'.id-2) method avoids risk of having same user name both accounts put in username before persist
i don't know start , method best. advice or idea helpful
ps:sorry english
my solution now
the user class
<?php namespace fm\fmbundle\entity; use doctrine\orm\mapping orm; use fos\userbundle\model\user baseuser; /** * @orm\entity * @orm\table(name="fos_user") */ class users extends baseuser { /** * @orm\id * @orm\column(type="integer") * @orm\generatedvalue(strategy="auto") */ protected $id; public function __construct() { parent::__construct(); // own logic } public function setemail($email){ parent::setemail($email); parent::setusername($email); } }
the post persist event listener
<?php namespace fm\fmbundle\eventlistener; use doctrine\orm\event\lifecycleeventargs; use doctrine\orm\event\postflusheventargs; class userpostpersistlistener { private $needsflush; public function __construct(){ $this->needsflush=false; } public function postpersist(lifecycleeventargs $args) { $user = $args->getentity(); $em = $args->getentitymanager(); if($user instanceof users) { $number=$user->getid()-2; $user->setusername('aa'.$number); } $em->persist($user); $this->needsflush = true; } public function postflush(postflusheventargs $eventargs) { if ($this->needsflush) { $this->needsflush = false; $eventargs->getentitymanager()->flush(); } } }
app/config/service.yml
fmarketuserpostpersistlistner: class: fm\fmbundle\eventlistener\userpostpersistlistener tags: - { name: doctrine.event_listener, event: postpersist }
app/config/security.yml
providers: fos_userbundle: id: fos_user.user_provider.username_email
but no thing happen username still same user email, when replace
if($user instanceof users) { $number=$user->getid()-2; $user->setusername('aa'.$number); }
by
$number=$user->getid()-2; $user->setusername('aa'.$number);
it work fine
i tried before if
dump(get_class($user)); dump($user instanceof users); die;
it give
userpostpersistlistener.php on line 17: "fm\fmbundle\entity\users" userpostpersistlistener.php on line 18: false
my question why class name of $user users not instance of users? , without if statement code executed every entity
Comments
Post a Comment