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

时间:2012-03-01 11:11:13

标签: validation passwords symfony twig formbuilder

这就是我的代码段的样子。

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

$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>

任何人都可以建议使用表单构建器的原因吗?

1 个答案:

答案 0 :(得分:8)

在Symfony 2中,验证由域对象处理。因此,您必须将实体(域对象)传递给表单。

控制器中的代码:

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()));
}

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

$registrationForm = $this->createFormBuilder($registration)...

2)bind将使用发布的所有数据来保存表单字段值

$registrationForm->bindRequest($request);

3)启动验证

$registrationForm->isValid()

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

return new RedirectResponse($this->generateUrl('registration_thanks'));

实体代码:

<?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;
    }
}

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

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