我可以在symfony5中将相同的信息从一个表单发送到2个操作吗?

xghobddn  于 2022-11-25  发布在  其他
关注(0)|答案(1)|浏览(118)

这是我的登录模板

{% extends 'base.html.twig' %}

{% block title %}Hello LoginController!{% endblock %}

{% block body %}
    {% if error %}
        <div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
    {% endif %}

    <form action="{{ path('app_login') }}" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="_username" value="{{ last_username }}"/>

        <label for="password">Password:</label>
        <input type="password" id="password" name="_password"/>

        <button type="submit">login</button>
    </form>
{% endblock %}

我想将信息发送给两个控制器
控制器1

#[Route('/consulta', name:'cita_consulta')]
    public function consultas(ManagerRegistry $doctrine)
    {
        $username=$_POST['_username'];
        $citaRepository = new CitaRepository($doctrine);
        $citas = $citaRepository->findAll();

        return $this->render('familia/reservas.html.twig', ['citas' => $citas,'username' => $username]);
    }

控制器2

#[Route('/login', name: 'app_login')]
    public function index(AuthenticationUtils $authenticationUtils): Response
        {
                // get the login error if there is one
                $error = $authenticationUtils->getLastAuthenticationError();
                // last username entered by the user
                $lastUsername = $authenticationUtils->getLastUsername();
                
                return $this->render('login/index.html.twig', ['last_username' => $lastUsername,'error'=> $error,]);
        }

我应该怎么做才能将信息发送到两个控制器?在1号控制器中,我需要以某种方式登录用户名,我想到使用$_POST ['_username']检索它

vlurs2pr

vlurs2pr1#

我想你要做的是让用户登录,然后给他们看他们的引用。这个想法不是发送两个表单,而是在登录被验证后进行重定向。

#[Route('/login', name: 'app_login')]
public function index(AuthenticationUtils $authenticationUtils): Response
{
        // get the login error if there is one
        $error = $authenticationUtils->getLastAuthenticationError();
        // last username entered by the user
        $lastUsername = $authenticationUtils->getLastUsername();
        
        if ($error) {
            return $this->render('login/index.html.twig', ['last_username' => $lastUsername,'error'=> $error,]);
        }

        return $this->redirectToRoute('cita_consulta', ['username' => $lastUsername], 301);
}

你可以通过参数传递用户名(我的例子),或者根据你的需要进行查询。然后,修改你的控制器1,通过参数获取用户名。

#[Route('/consulta/{username}', name:'cita_consulta')]
public function consultas(string $username, ManagerRegistry $doctrine)
{
    $citaRepository = new CitaRepository($doctrine);
    $citas = $citaRepository->findAll();

    return $this->render('familia/reservas.html.twig', ['citas' => $citas,'username' => $username]);
}

相关问题