Symfony2表单集合

时间:2014-04-22 14:02:40

标签: forms symfony collections symfony-forms

我在我的数据库中有这个:

A product vitamin contains a product, a vitamin and a value

现在,我希望能够通过单一形式添加产品和product_vitamins:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name', null, array(
        'description' => 'The name of the product'));

    $builder->add('product_vitamins', 'collection', array(
        'type'  => new ProductVitaminType(),
        'allow_add'   => true,
    ));
}

我的ProductVitaminType如下所示:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('vitamin_id', null, array(
        'description'   => 'The vitamin id'));

    $builder->add('value', null, array(
        'description' => 'The value of this vitamin'));

    $builder->addEventSubscriber(new PartialFormBindSubscriber());
}

我将此发送到我的后端,所有属性(也是关系)都将正确填充:

{
    "food_product" : {
        "name" : "foo",
        "product_vitamins" : [
            {"vitamin_id" :  9, "value" : 52},
            {"vitamin_id" :  4, "value" : 52},
            {"vitamin_id" :  5, "value" : 52},
            {"vitamin_id" :  2, "value" : 52},
            {"vitamin_id" :  8, "value" : 52}
        ]
    }
}

但是,product_vitamins的product_id为null,因此我在持久化时遇到此错误:

Unable to execute INSERT statement [INSERT INTO `Food_Product_Vitamin` (`vitamin_id`, `value`, `created_at`, `updated_at`) VALUES (:p0, :p1, :p2, :p3)] [wrapped: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`Food_Product_Vitamin`, CONSTRAINT `Food_Product_Vitamin_product_id` FOREIGN KEY (`product_id`) REFERENCES `Food_Product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)]

我不明白这个问题,因为它应该首先保存产品,然后它应该有product_id。

更新:控制器操作

public function putProductsAction(Request $request)
{
    $model = new Product();
    $type  = new ProductType();
    $form  = $this->formFactory->create($type, $model);

    return $form->isValid() ? $model->save() : $form;
}

0 个答案:

没有答案