简体   繁体   English

如何将Symfony2表单与数组(不是请求)绑定?

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

Let say I have an HTML form with bunch of fields. 假设我有一个包含大量字段的HTML表单。 Some fields belong to Product, some to Order, some to Other. 有些字段属于Product,有些属于Order,有些属于Other。 When the form is submitted I want to take that request and then create Symfony forms for Product, Order, and Other in controller. 提交表单时,我想接受该请求,然后在控制器中为Product,Order和Other创建Symfony表单。 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. 问题是,当我尝试这样做时,我无法使用$ form-> isValid()方法。 It seems that bind() step fails. 似乎bind()步骤失败了。 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). 再次,我在视图中构建自己的HTML表单(我没有使用form_widget(),导致将一堆FormTypes以某种方式合并到一起所需的所有复杂性)。 I just want a very simple way to use basic HTML form together with Symfony form feature set. 我只想要一个非常简单的方法来使用基本的HTML表单和Symfony表单功能集。

Can anyone tell me is this even possible with Symfony and how do I go about doing it? 任何人都可以告诉我,Symfony甚至可以做到这一点,我该怎么做呢?

You need to disable CSRF token to manually bind data. 您需要禁用CSRF令牌以手动绑定数据。

To do this you can pass the csrf_protection option when creating form object. 为此,您可以在创建表单对象时传递csrf_protection选项。

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. 就像这样你只需要将一个对象与请求绑定,并通过简单的getter访问嵌入对象。

Am I clear enough? 我清楚了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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