简体   繁体   中英

Symfony2: How to persist a new User in an admin-interface with FOSUserBundle?

I'm creating the admin view where i can list the users and create the users. I have created the User class but i am not sure how can i persist it.

Do I need to manually create the form and then persist it?

I have saved using normal save but then there is validation performed.

I want to know wether I need to manually encode password etc. or FOSUserBundle will do that for me.

I assume that your aren't planning to use ...

  • the default /register route / method for new users
  • the console command : app/console fos:user:create testuser test@example.com p@ssword

... as you're talking about an admin (web)-interface.


Answer:

In a ContainerAware class (ie controllers) ...

... you can re-use the default registration-form and disable validation:

$user = new User();
$this->createForm(
    $this->get('fos_user.registration.form.type'),
    $user,
    array(
       'validation_groups' => false,
    )
);

Here's how to manually create a new User and persist it to the database:

$om      = $this->container->get('doctrine.orm.entity_manager');     
$manager = $this->container->get('fos_user.user_manager');

$user = $manager->createUser();

$user
    ->setUsername('nifr')
    ->setEmail('dont@spam.me')
    ->setPlainPassword('Insecure123')
    ->setEnabled(true)
;

$om->persist($user);
$om->flush();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM