Symfony fosuserbundle add Account entity to a person entity

会有一股神秘感。 提交于 2019-12-13 17:26:29

问题


I have a Symfony project with FOSUserBundle, i extended the FormType in my personal Bundle following this guide "http://symfony.com/doc/master/bundles/FOSUserBundle/overriding_forms.html"

I created a Person entity with first name, last name, adresse ..., created its FormType like this :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('firstName', TextType::class)
            ->add('lastName', TextType::class)
            ->add('adress', TextType::class)
            ->add('account', AccountType::class) ;
}

The Account entity is the user class for FOSUserBundle

Then i generated the CRUD for Person, the newAction() looks like this :

public function newAction(Request $request)
{
    $person = new Person();
    $form = $this->createForm('AppBundle\Form\PersonType', $person);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $person->getAccount()->setEnabled(1); //i'm doing this because it's not automatic
        $em->persist($person->getAccount());
        $em->persist($person);
        $em->flush($person);

        return $this->redirectToRoute('fos_user_security_login'); // redirecting to the login page because it's not done automatically
    }
    return $this->render('person/new.html.twig', array(
        'person' => $person,
        'form' => $form->createView(),
    ));
}

The two entitys have a OneToOne relationship, with this code they are both persisted in the data base and i can use the username and password to log in normally

Here is my FOSUerBundle configuration :

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: AppBundle\Entity\Account
    from_email:
        address: "%mailer_user%"
        sender_name: "%mailer_user%"
    registration:
        form:
            type: AppBundle\Form\AccountType

I want to the user to log in automatically after registration like it happens when using the default FOSUserBundle registration, anyone got an idea how to do so ?

I tried a lot of stuff but no success

Thanks for your answers


回答1:


I was able to login from my controller using the $person->getAccount() object:

All i have to do is dispatch the REGISTRATION_COMPLETED event like in the default Controller : https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/RegistrationController.php#L78

Just copied some code to my controller

This will trigger the authentication : https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/EventListener/AuthenticationListener.php



来源:https://stackoverflow.com/questions/42876465/symfony-fosuserbundle-add-account-entity-to-a-person-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!