【问题标题】:Rendering multiple forms on same page with Symfony 3使用 Symfony 3 在同一页面上呈现多个表单
【发布时间】:2016-07-05 18:42:20
【问题描述】:

我想在同一页面上显示登录信息和注册表单。但是,我们似乎无法在控制器中的不同两个动作中呈现具有不同表单变量的相同模板。

这就是我的意思;

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('no-reply@kampweb.com')
                ->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,
            )
    );
}

}

上面我有我的登录和注册操作。我想将“表单”变量传递给我使用登录操作呈现的同一个树枝模板。当我尝试这样做时,我得到了以下异常。

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

【问题讨论】:

  • 您没有将任何form 变量传递给loginAction 中的视图。你注意到了吗?这就是您收到错误的原因。
  • 是的。抱歉,在发布之前忘记删除该更新。现在我更新了这个问题。我正在尝试在两个操作中呈现相同的模板。

标签: php forms symfony


【解决方案1】:

我会这样做

2 个树枝文件 -

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

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

在这个文件中,我通过调用控制器来渲染两个文件(登录和注册)

例如

baseLogin.html.twig

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

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

【讨论】:

  • 这是一个好方法,但是我仍然无法在 baseLogin.html.twig 页面上显示错误。当用户点击登录或注册链接时,他们将被重定向到 /login 或 /register 页面。我需要在 baseLogin 页面上呈现所有操作。
  • 在表单上设置操作选项以编辑目标。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2016-09-05
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多