如何在Symfony中嵌入表单集合?

时间:2017-05-10 19:17:05

标签: php forms symfony

我在尝试创建嵌入另一个实体集合的表单时遇到了一些问题。

我想创建一个食谱,为此我希望用户能够为该食谱插入几个标签。

我已经关注了当前Symfony documentation,我实际上能够插入两个实体Recipe和Tag,但对于Tag实体,实际上只插入了id。

这是我到目前为止所做的:

RecipeType 表单:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name')
        ->add('recipe_tags', CollectionType::class, array(
            'entry_type' => TagsType::class,
            'allow_add' => true,
            'by_reference' => false,
        ));

}

其中添加了collat​​edType TagsType 表单,其编码如下:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name');
}

然后我事先在控制器中创建一个标记对象,这样配方实体就有一个默认标记,在提交表单后会更新。

    $recipe = new Recipe();
    $tag = new Tags();
    $tag->setName('tag1');
    $recipe->addRecipeTag($tag);
    $form = $this->get('form.factory')->createNamed(null, RecipeType::class, 
    $recipe);

最后,食谱实体与(我认为如此)正确的信息:

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="Tags", inversedBy="idRecipe", cascade=
 {"persist"})
 * @ORM\JoinTable(name="recipe_tags",
 *   joinColumns={
 *     @ORM\JoinColumn(name="id_recipe", referencedColumnName="id_recipe")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="id_tag", referencedColumnName="id_tag")
 *   }
 * )
 * @Groups({"recipe_detail"})
 *
 */
private $recipe_tags;

我在文档后面添加了级联持久注释。这是添加标签的方法。

/**
 * Add recipeTag
 *
 * @param \AppBundle\Entity\Tags $recipeTag
 *
 * @return Recipe
 */
public function addRecipeTag(\AppBundle\Entity\Tags $recipeTag)
{
    $this->recipe_tags[] = $recipeTag;

    return $this;
}

这就是我插入到我的数据库中的内容(是POST请求后的返回):

 {
"recipe": {
"idRecipe": 3671,
"name": "TagName#76232",
"description": null,
"duration": null,
"updatedAt": null,
"createdAt": null,
"active": null,
"image": null,
"portions": null,
"idCategory": null,
"createdBy": null,
"recipeTags": [
  {
    "idTag": 143,
    "name": null
  }
],
"recipeSteps": [],
"recipeIngredients": null

} }

如您所见,配方已正确添加,但我刚刚创建的标签没有添加任何名称。此外,数据透视表 recipe_tags 根本不会添加数据。

我做错了什么?

修改

我认为问题在于我为两个实体使用了相同的表单名称字段。现在我已经更改了字段并出现了一个新错误:

{
  "code": 400,
  "message": "Validation Failed",
  "errors": {
  "errors": [
    "This value is not valid."
   ],
  "children": {
    "name": [],
    "recipe_tags": {
      "children": [
        {
          "children": {
            "tag": []
        }
      }
    ]
  }
}

} }

这是我通过POST请求传递的参数:

{"name":"Recipe#2342"}
{"recipe_tags":"TagName#76232"}

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:1)

使用ManyToMany,您只需在EntityType中添加一个multiple=true字段RecipeType即可完成,除非您还要创建新标记。

相关问题