1

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 string $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] => '[email protected]')

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

0

3 Answers 3

1

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

array ( [user] => Array ( [email] => [email protected] ) )
1

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

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.