php - 使用 Symfony 3 在同一页面上呈现多个表单

标签 php forms symfony

我想在同一页面上显示登录名和注册表单。然而,我们似乎无法在 Controller 中的不同两个操作中呈现具有不同表单变量的相同模板。

这就是我的意思;

class SecurityController extends Controller { 
/**
 * @Route("/", name="login")
 */
public function loginAction(Request $request)
{

    //Check if the user is already authenticated
    if($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
        return $this->redirect($this->generateUrl('dashboard'));
    }

   $authenticationUtils = $this->get('security.authentication_utils');

    // get the  error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();

    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    $this->addFlash(
        'welcome',
        'Welcome back!'
    );

    return $this->render(
        '::landing.html.twig',
        array(
            // last username entered by the user
            'last_username' => $lastUsername,
            'error'         => $error,
        )
    );

    $registrationform = $this->get('form.factory')->createNamedBuilder('registrationform', UserType::class);
}

/**
 * @Route("/register", name="register")
 */
public function registerAction(Request $request)
{
    //Check authentication
    if($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
        return $this->redirect($this->generateUrl('dashboard'));
    }
    // get the authentication utils
    $authenticationUtils = $this->get('security.authentication_utils');
    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();
    // build the form
    $user = new User();
    $form = $this->createForm(UserType::class, $user);
        // handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $user->setRoles(array('ROLE_USER'));
            // Encode the password (you could also do this via Doctrine listener)
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

            // save the User!
            $em = $this->getDoctrine()->getManager();
            $em->persist($user);
            $em->flush();

            $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
            $this->get('security.token_storage')->setToken($token);
            $this->get('session')->set('_security_main', serialize($token));
            // ... do any other work - like sending them an email, etc
            // maybe set a "flash" success message for the user

            $this->addFlash(
                'success',
                'Please complete your profile now.'
            );

            $message = \Swift_Message::newInstance()
                ->setSubject('You have successfully signed up!')
                ->setFrom('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="533d3c7e2136233f2a1338323e232436317d303c3e" rel="noreferrer noopener nofollow">[email protected]</a>')
                ->setTo($user->getUsername())
                ->setBody($this->renderView(
                    ':emails:registration.html.twig'),'text/html');
            $this->get('mailer')->send($message);

            return $this->redirectToRoute('update');
        } else{
            $errors = $this->get('validator')->validate( $user );
        }

    return $this->render(
        '::landing.html.twig',
        array( 'form' => $form->createView(),
            'last_username' => $lastUsername,
            'error' => $error,
            )
    );
}

}

上面是我的登录和注册操作。我想将“form”变量传递给我使用登录操作呈现的同一 Twig 模板。当我尝试这样做时,我收到以下异常。

Variable "form" does not exist in ::landing.html.twig at line 50
500 Internal Server Error - Twig_Error_Runtime

最佳答案

我会这样做

2 个 Twig 文件 -

login.html.twig 和 register.html.twig - 每个文件都自行渲染操作

现在第三个 Twig 文件名为baseLogin.html.twig

在此文件中,我通过调用 Controller 渲染两个文件(登录和注册)

例如

baseLogin.html.twig

<div>
    {{ render(controller('UserBundle:Security:login')) }}
</div>

<div>
    {{ render(controller('UserBundle:Registration:register')) }}
</div>

关于php - 使用 Symfony 3 在同一页面上呈现多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38210457/

相关文章:

javascript - 确保 TD 输入值不超过之前的 TD 值

javascript - 通过 ajax 将变量从表单 (POST) 发送到另一个 PHP 脚本 (GET)

PHP 和错误 "start-stop-daemon: unable to stat"

php - 如何显示用户配置文件中的 acf 字段?

php - 在 Codeigniter 中的所有 Controller 上具有固定 View

php - Sonata Admin - 更改订单父类别

php - Symfony 新包无法找到模板

php - 在 Swift 中为聊天应用程序保持套接字打开

c# - 在 Windows 服务和 Windows 应用程序之间使用 EventWaitHandles

php - 用于searchly.com的Elasticsearch PHP连接设置