Symfony 5 - 同一页面上的多个表单

2022-01-22 00:00:00 forms php symfony twig

我使用 Symfony 5.

I use Symfony 5.

我有 2 个表单呈现在同一页面中:登录表单和注册表单.

I have 2 forms that is rendered in the same page : Login Form and Registration Form.

论文 2 表单被调用到 SecurityController 中.我想知道的是,如何在同一页面中使用这两个表单?当我执行注册表时,登录表单出现错误.

Theses 2 forms are called into a SecurityController. What I want to know is, how can I use theses 2 forms in the same page? When I execute Registration Form, I have error from the Login Form.

这是我的文件.

SecurityController.php

<?php

namespace AppController;

use AppEntityUser;
use AppFormLoginFormType;
use AppFormRegistrationFormType;
use LeagueCsvReader;
use LeagueCsvStatement;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentForm;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use SymfonyComponentSecurityHttpAuthenticationAuthenticationUtils;

class SecurityController extends AbstractController
{
    /**
     * @Route("/login", name="login")
     */

    public function login(Request $request, AuthenticationUtils $utils, UserPasswordEncoderInterface $passwordEncoder) : Response
    {

        $user = new User();
        $registerForm = $this->createForm(RegistrationFormType::class, $user);
        $loginForm = $this->createForm(LoginFormType::class, $user);
        $error = $utils->getLastAuthenticationError();

        if($request->isMethod('POST')){
            $registerForm->handleRequest($request);
            $loginForm->handleRequest($request);

            if($request->get('signUp', null)){
                if ($registerForm->isSubmitted() && $registerForm->isValid()) {
                    // encode the plain password
                    $user->setPassword(
                        $passwordEncoder->encodePassword(
                            $user,
                            $registerForm->get('password')->getData()
                        )
                    );

                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->persist($user);
                    $entityManager->flush();

                    return $this->redirectToRoute('');
                }
            }

            if($request->get('signIn', null)){
                if($loginForm->isSubmitted() && $loginForm->isValid()){

                }
            }
        }

        /*$reader = Reader::createFromPath('../src/CSVDATA/dbigo.csv','r');
        foreach ($reader->getRecords(['Last name', 'First name  ', 'SSN']) as $row){

        }*/

        return $this->render('pages/login.html.twig', [
            'registrationForm' => $registerForm->createView(),
            'loginForm' => $loginForm->createView(),
            'error' => $error,
        ]);
    }



    /**
     * @Route("/logout", name="logout")
     */
    public function logout(){

    }
}

RegistrationFormType.php

<?php

namespace AppForm;

use AppEntityUser;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypePasswordType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsLength;
use SymfonyComponentValidatorConstraintsNotBlank;

class RegistrationFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('username', TextType::class,
                [
                'attr' => [
                    'class' => 'form-control',
                    'placeholder' => 'Your username'
                ]
            ])
            ->add('email', EmailType::class,
            [
                'attr' => [
                    'class' => 'form-control',
                    'placeholder'=> 'Your email',
                ]
            ])
            ->add('password', PasswordType::class, [
                // instead of being set onto the object directly,
                // this is read and encoded in the controller
                'attr' => [
                  'class' => 'form-control',
                  'placeholder' => 'Your password'
                ],
                'mapped' => false,
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                    new Length([
                        'min' => 6,
                        'minMessage' => 'Your password should be at least {{ limit }} characters',
                        // max length allowed by Symfony for security reasons
                        'max' => 4096,
                    ]),
                ],
            ])
            ->add('signUp', SubmitType::class,[
                'label' => 'Sign up',
                'attr' => [
                    'class' => 'btn btn-lg btn-primary btn-block'
                ]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }

    public function getBlockPrefix()
    {
        return 'registration_Form';
    }
}

LoginFormType.php

<?php

namespace AppForm;

use AppEntityUser;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeEmailType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypePasswordType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsNotBlank;

class LoginFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class,
                [
                    'attr' => [
                        'class' => 'form-control',
                        'placeholder' => 'Your email',
                    ],
                ])
            ->add('password', PasswordType::class, [
                // instead of being set onto the object directly,
                // this is read and encoded in the controller
                'attr' => [
                    'class' => 'form-control',
                    'placeholder' => 'Your password'
                ],
                'mapped' => false,
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                ],
            ])
            ->add('signIn', SubmitType::class,[
                'label' => 'Sign in',
                'attr' => [
                    'class' => 'btn btn-lg btn-primary btn-block'
                ]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

User.php

<?php

namespace AppEntity;

use DoctrineORMMapping as ORM;
use SymfonyBridgeDoctrineValidatorConstraintsUniqueEntity;
use SymfonyComponentSecurityCoreUserUserInterface;

/**
 * @ORMEntity(repositoryClass="AppRepositoryUserRepository")
 * @UniqueEntity(fields={"username"}, message="There is already an account with this username")
 */
class User implements UserInterface, Serializable
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer", unique=true)
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $username;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $password;

    /**
     * @ORMColumn(type="string", length=255)
     */
    private $email;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getRoles()
    {
        return [
            "ROLE_USER"
        ];
    }

    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    public function eraseCredentials()
    {
        // TODO: Implement eraseCredentials() method.
    }

    public function serialize()
    {
        return serialize([
            $this->id,
            $this->username,
            $this->email,
            $this->password,
        ]);
    }

    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->username,
            $this->email,
            $this->password,
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}

login.html.twig

(...)
                    <!-- Login form -->
                    <div class="row">
                        <div class="col-xs-12 col-sm-12">
                            <form action="{{ path('login') }}" method="POST" class="login-Form">
                                {{ form_start(loginForm) }}
                                <div class="form-group wrap-input">
                                    {{ form_widget(loginForm.email) }}
                                    <span class="focus-input"></span>
                                </div>
                                <div class="form-group wrap-input">
                                    <div class="pwdMask">
                                        {{ form_widget(loginForm.password) }}
                                        <span class="focus-input"></span>
                                        <span class="fas pwd-toggle fa-eye-slash"></span>
                                    </div>
                                </div>
                                <!-- Remember row -->
                                <div class="row remember-row">
                                    <div class="col-xs-6 col-sm-6  text-left">
                                        <label class="checkbox">
                                            <input type="checkbox" name="_remember_me"><span class="label-text">Remember Me</span>
                                        </label>
                                    </div>
                                    <div class="col-xs-6 col-sm-6 text-right">
                                        <p class="forgotPwd">
                                            <a href="#" class="lnk-toggler" data-panel=".forget-panel">Forgot password?</a>
                                        </p>
                                    </div>
                                </div>
                                <!-- /Remember row-->
                                <div class="form-group">
                                    {{ form_widget(loginForm.signIn) }}
                                </div>
                                {{ form_end(loginForm) }}
                            </form>
                        </div>
                    </div>
                    <!-- /Login form -->
                </div>
                <!-- /Login Panel -->

                <!-- Sign up Panel -->
(---)
                            <form action="{{ path('login') }}" method="POST" class="signupForm">
                                {{ form_start(registrationForm) }}
                                <div class="form-group wrap-input">
                                    <!-- <input type="text" class="form-control" name="_username" placeholder="Your email"> -->
                                    {{ form_widget(registrationForm.username) }}
                                    <span class="focus-input"></span>
                                </div>
                                <div class="form-group wrap-input">
                                    <!-- <input type="text" class="form-control" name="_email" placeholder="Your access code"> -->
                                    {{ form_widget(registrationForm.email) }}
                                    <span class="focus-input"></span>
                                </div>
                                <div class="form-group wrap-input">
                                    <div class="pwdMask">
                                        {{ form_widget(registrationForm.password) }}
                                        <!-- <input type="password" class="form-control" name="_password" placeholder="Your password"> -->
                                        <span class="focus-input"></span>
                                        <span class="fas fa-eye-slash pwd-toggle"></span>
                                    </div>
                                </div>
                                <div class="form-group">
                                    {{ form_widget(registrationForm.signUp) }}
                                </div>
                                {{ form_end(registrationForm) }}
                            </form>
                <!-- /Sign up Panel -->
(...)

我已经感谢你的帮助 :D

I already thank you for your help :D

B.

推荐答案

只要使用这部分代码就可以了

Just use this part of code and it works

if($loginForm->isSubmitted() && $loginForm->isValid()){
  //code
  //don't forget the return statement
}

if($registerForm->isSubmitted() && $registerForm->isValid()){
  //code
  //don't forget the return statement
}

相关文章