Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind Symfony2 form with an array (not a request)?

Tags:

php

symfony

Let say I have an HTML form with bunch of fields. Some fields belong to Product, some to Order, some to Other. When the form is submitted I want to take that request and then create Symfony forms for Product, Order, and Other in controller. Then I want to take partial form data and bind it with appropriate forms. An example would something like this:

$productArray = array('name'=>$request->get('name'));
$pf = $this->createForm(new \MyBundle\Form\ProductType(), $product);
$pf->bind($productArray);
if($pf->isValid()) {
  // submit product data
}

// Do same for Order (but use order data)

// Do same for Other (but use other data)

The thing is when I try to do it, I can't get $form->isValid() method working. It seems that bind() step fails. I have a suspicion that it might have to do with the form token, but I not sure how to fix it. Again, I build my own HTML form in a view (I did not use form_widget(), cause of all complications it would require to merge bunch of FormTypes into one somehow). I just want a very simple way to use basic HTML form together with Symfony form feature set.

Can anyone tell me is this even possible with Symfony and how do I go about doing it?

like image 947
user1863635 Avatar asked Nov 02 '22 23:11

user1863635


1 Answers

You need to disable CSRF token to manually bind data.

To do this you can pass the csrf_protection option when creating form object.

Like this:

$pf = $this->createForm(new \MyBundle\Form\ProductType(), $product, array(
    'csrf_protection' => false
));
like image 66
Inoryy Avatar answered Nov 09 '22 08:11

Inoryy