1

これが私のコードスニペットのようです。

//---これは私のコントローラーのコードです----

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

フォームビルダーを使用して機能しない理由を誰かが提案できますか?

4

1 に答える 1

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->bindRequest($request);

3)検証を開始するには

$registrationForm->isValid()

4)投稿されたデータが有効な場合は、データを再投稿するかどうかを尋ねるブラウザからのアラートメッセージが表示されないように、すべてが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;
    }
}

検証用のドキュメント:http ://symfony.com/doc/current/book/validation.html

注:パスワードエンティティプロパティに検証を追加する必要はありません。repatedTypeによって検証が行われます。

于 2012-04-25T21:52:42.000 に答える