Forms Symfony2表格集合

Forms Symfony2表格集合,forms,symfony,collections,symfony-forms,Forms,Symfony,Collections,Symfony Forms,我的数据库中有以下内容: 现在,我想通过一种形式添加产品和产品维生素: public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name', null, array( 'description' => 'The name of the product')); $builder->add('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_的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)]
我不理解这个问题,因为它应该先保存产品,然后才应该有产品id

更新:控制器操作
请添加控制器的代码。嘿。我添加了控制器代码。请参阅将维生素与产品关联。我从您发布的文档网站获得了代码。你能更详细地解释一下你的答案吗?在你的控制器里,你没有任何关联。但是您似乎是在
$model->save()
中执行此操作的,您可以添加此代码吗?
public function putProductsAction(Request $request)
{
    $model = new Product();
    $type  = new ProductType();
    $form  = $this->formFactory->create($type, $model);

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