使用symfony2中的表单构建器使用"重复"字段确认密码字段未验证?

Shr*_*tty 1 passwords validation formbuilder symfony twig

这就是我的代码片段的样子.

// ---这是我控制器中的代码----

$registrationForm = $this->createFormBuilder()
                ->add('email')
                ->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Passwords do not match'))
                ->getForm();

        return $this->render('AcmeHelloBundle:Default:index.html.twig', array('form' => $registrationForm->createView()));

// --- This is the twig file code----

<form action="#" method="post" {{ form_enctype(form) }}>
    {{ form_errors(form) }}
    {{ form_row( form.email, { 'label': 'E-Mail:' } ) }}
    {{ form_errors( form.password ) }}
    {{ form_row( form.password.first, { 'label': 'Your password:' } ) }}     
    {{ form_row( form.password.second, { 'label': 'Repeat Password:' } ) }}     
    {{ form_rest( form ) }}
    <input type="submit" value="Register" />
</form>
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议为什么它不能使用表单构建器?

小智 8

在Symfony 2中,验证由域对象处理.所以你必须将一个Entity(域对象)传递给你的表单.

控制器中的代码:

public function testAction()
{
    $registration = new \Acme\DemoBundle\Entity\Registration();
    $registrationForm = $this->createFormBuilder($registration)
            ->add('email')
            ->add('password', 'repeated', array('type' => 'password', 'invalid_message' => 'Passwords do not match'))
            ->getForm();

    $request = $this->get('request');
    if ('POST' == $request->getMethod()) {
        $registrationForm->bindRequest($request);
        if ($registrationForm->isValid()) {
            return new RedirectResponse($this->generateUrl('registration_thanks'));
        }
    }

    return $this->render('AcmeDemoBundle:Demo:test.html.twig', array('form' => $registrationForm->createView()));
}
Run Code Online (Sandbox Code Playgroud)

1)表单构建器将使用实体的属性映射表单字段,并使用您的实体属性值来保存表单字段值.

$registrationForm = $this->createFormBuilder($registration)...
Run Code Online (Sandbox Code Playgroud)

2)绑定将使用发布的所有数据水合您的表单字段值

$registrationForm->bindRequest($request);
Run Code Online (Sandbox Code Playgroud)

3)启动验证

$registrationForm->isValid()
Run Code Online (Sandbox Code Playgroud)

4)如果发布的数据有效,您必须重定向到一个操作以通知用户一切正常,以避免显示来自您的broswer的警报消息,询问您是否确定要重新发布数据.

return new RedirectResponse($this->generateUrl('registration_thanks'));
Run Code Online (Sandbox Code Playgroud)

实体代码:

<?php

namespace Acme\DemoBundle\Entity;

class Registration
{
    private $email;

    private $password;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }
}
Run Code Online (Sandbox Code Playgroud)

验证文件:http://symfony.com/doc/current/book/validation.html

注意:无需在密码实体属性上添加一些验证,repeatType为您完成