简体   繁体   中英

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

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?

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

I feel like you might need a form that embed the other forms:

// Main form
$builder
    ->add('product', new ProductType)
    ->add('order', new OrderType);

and have an object that contains association to these other objects to which you bind to the request. Like so you just have to bind one object with the request and access embedded object via simple getters.

Am I clear enough?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM