Search code examples
symfonydoctrinefosuserbundlesonata-adminsonata-user-bundle

How to create user with fixtures with sonata admin


I started my application in Symfony 4.2 with FOSUserBundle and made a fixture file to create the admin.

use FOS\UserBundle\Doctrine\UserManager;
...
/** @var UserManager $userManager */
$userManager = $this->getContainer()->get('fos_user.user_manager');
/** @var User $user */
$user = $userManager->createUser();
$user
    ->setUsername('username')
    ->setEmail('email')
    ->setPlainPassword('password')
    ->setSuperAdmin(true);
$manager->persist($user);
$manager->flush();

It worked fine, but then I decided to user SonataAdmin and ACL.

Since then, I can't login anymore with the admin.

But if I create the admin user with the bin/console fos:user:create --super-admin command, instead the one from the fixture file, I can login normally.

Checking the database, the only differences between the two users are the salt and the password hash, but that's expected.

That said, can anybody explain what I need to change in the fixture file for it to create a working admin user?

Thanks in advance.


Solution

  • The answer is in FOS\UserBundle\Command\CreateUserCommand. You need to use the FOS\UserBundle\Util\UserManipulator to create the user.

    use FOS\UserBundle\Util\UserManipulator;
    
    ...
    
    /** @var UserManipulator $userManipulator */
    $userManipulator = $this->getContainer()->get('fos_user.util.user_manipulator');
    
    $user = $userManipulator->create( 'username', 'password', 'email', true, true);