在无效表单提交上使用不同的路由

时间:2015-10-24 21:01:05

标签: php forms symfony twig

我正在构建一个包含多个表单的页面。现在,当我输入密码不匹配时,例如我进入错误的路线,即表格所在的位置,而不是我呈现它的页面。

我如何正确地解决这个问题?

html结构,省略了“管理”页面,这些页面全部加载在

#app/Resources/views/forms/user.html.twig
{{ form_start(form) }}
{{ form_widget(form) }}
<button type="submit" class="btn btn-primary pull-right">Submit</button>
{{ form_end(form) }}

#app/Resources/views/components/management/user/user.html.twig
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6">
           {% include 'components/management/user/list.html.twig' %}
        </div>
        <div class="col-md-6">
            {% include 'components/management/user/add.html.twig' %}
        </div>
    </div>
</div>

#app/Resources/views/components/management/user/add.html.twig
<table class="table">
    <thead id="add-user-head" class="pointer">
    <tr>
        <th>Add user <span id="caret-add-user" class="caret"></span></th>
    </tr>
    </thead>

    <tbody id="add-user-body">
    <tr>
        <td>
            {{ render(controller('AppBundle:Manage:user')) }}
        </td>
    </tr>
    </tbody>
</table>

Controller,省略了表单构建器

#@AppBundle/Controller/ManageController.php
public function viewAction()
    {
        return $this->render('pages/management.html.twig', array('users' => $this->listUsers()));
    }

    public function userAction(Request $request)
    {
        // 1) build the form
        $user = new User();
        $form = $this->createForm(new UserType(), $user, array(
            'action' => $this->generateUrl('manage_user'),
            'method' => 'GET'
        ));

        // 2) handle the submit (will only happen on POST)
        $form->handleRequest($request);

        if ($form->isValid() && $form->isSubmitted()) {
            // 3) Encode the password (you could also do this via Doctrine listener)
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

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

            // ... do any other work - like send them an email, etc
            // maybe set a "flash" success message for the user

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

        return $this->render('forms/user.html.twig', array('form' => $form->createView()));
    }

为了澄清一点:由于表单操作,无效的输入会将我带到forms / user.html.twig页面。

1 个答案:

答案 0 :(得分:0)

我认为你只需要另一个其他声明,但我不确定你想要重定向到哪里:

if ($form->isValid() && $form->isSubmitted()) {
        // same stuff
    } elseif ($form->isSubmitted()) {
        return $this->redirectToRoute('invalidSubmission');
    }