本文介绍了Symfony 5-同一页面上的倍数形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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中.我想知道的是,如何在同一页面中使用这2种形式?当我执行注册表单时,登录表单中出现错误.

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 App\Controller;

use App\Entity\User;
use App\Form\LoginFormType;
use App\Form\RegistrationFormType;
use League\Csv\Reader;
use League\Csv\Statement;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

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 App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

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 App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;

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 App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity(fields={"username"}, message="There is already an account with this username")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer", unique=true)
     */
    private $id;

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

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

    /**
     * @ORM\Column(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
}

这篇关于Symfony 5-同一页面上的倍数形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:10