开发者

Symfony2 form - data never bound to it

I have a simple form in Symfony2 (beta 5), but the post data is never bound to the form. Here are my classes (trimmed for brevity):

/**
 * Represents a User
 *
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks()
 */
class User
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;
    /**
     * @ORM\Column(type="string", unique="true", length="150")
     * @Assert\Email()
     */
    protected $email;

    /**
     * @param stri开发者_如何学Pythonng $email
     */
    public function setEmail($email)
    {
        $this->email = $email;
    }

    /**
     * @return string $email
     */
    public function getEmail()
    {
        return $this->email;
    }
}

The form builder:

class UserType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('email');
    }
}

The action:

public function addAction()
{
    $request = $this->getRequest();

    if ($request->getMethod() == 'POST')
    {
        $user = new User();
        $form = $this->createForm(new UserType(), $user);
        $form->bindRequest($request);
print_r($_POST);        // fine - contains an email address
echo 'email: ';
print_r($user->getEmail());              // always empty
        if ($form->isValid())            // never valid
        {
             // ....

Post data:

array([email] => 'test@test.com')

What's wrong with my set-up? This is the second form I've made with a different model, so I'm obviously doing something wrong.

Is it perhaps that I'm posting 'email' as the key instead of something more elaborate like 'user_email'? I haven't rendered the form - I'm just submitting post data by hand because this is for a web service.

Thanks


the problem was with my post data. it should have been:

array ( [user] => Array ( [email] => test@tests.com ) )


You should try to add this method in your UserType form:

public function getDefaultOptions(array $options)
{
    return array(
        'data_class' => 'User',
    );
}


Are you using the form builder to create the form? The form build expects the name to follow a certain format, not just have an email field. You would normally create the form, then check if the request is a Post, if not render the form in the template.

$form = $this->createForm(new UserType(), $user);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
     $form->bindRequest($request);
     ...
     return...
}
return array('form' => $form->createView());

Then in your template you use {{ form_widget(form) }} or the related functions that allow you to render parts of the form.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜