2012-03-01 5 views
1

これは私のコードスニペットの様子です。パスワードフィールドの確認がsymfony2のフォームビルダーを使用して '繰り返し'フィールドを使用して検証していませんか?

// ---これは、フォームビルダを使用して動作していない理由を

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

は、いずれかがお勧めできます----私のコントローラ内のコードですか?

答えて

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)ポストされたデータが有効である場合、バインドは、)

$registrationForm->isValid() 

4検証を起動するには)

$registrationForm->bindRequest($request); 

3投稿されたすべてのデータを使用してフォームフィールドの値を水和しますあなたは、あなたがデータを再投稿することが確実であるかどうかを尋ねるブローワーからの警告メッセージを表示しないように、すべてがOKであることをユーザーに知らせるアクションにリダイレクトする必要があります。

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

はDOC:http://symfony.com/doc/current/book/validation.html

注:パスワードのエンティティプロパティにいくつかの検証を追加する必要がない、repeatedTypeはあなた

+0

のためにそれをやっあなたが助けてくれてありがとう。 – GorillaApe

関連する問題