php - Symfony实体字段: manyToMany with multiple = false - field not populated correctly

标签 php forms symfony doctrine-orm entity

我正在使用 symfony2 和原则 2。 我在两个实体之间有多对多关系:

/**
 * @ORM\ManyToMany(targetEntity="\AppBundle\Entity\Social\PostCategory", inversedBy="posts")
 * @ORM\JoinTable(
 *     name="post_postcategory",
 *     joinColumns={@ORM\JoinColumn(name="postId", referencedColumnName="id", onDelete="CASCADE")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="postCategoryId", referencedColumnName="id", onDelete="CASCADE")}
 * )
 */
private $postCategories;

现在我想让用户只选择一个类别。为此,我在表单中使用选项 'multiple' => false。

我的表格:

        ->add('postCategories', 'entity', array(
                'label'=> 'Catégorie',
                'required' => true,
                'empty_data' => false,
                'empty_value' => 'Sélectionnez une catégorie',
                'class' => 'AppBundle\Entity\Social\PostCategory',
                'multiple' => false,
                'by_reference' => false,
                'query_builder' => $queryBuilder,
                'position' => array('before' => 'name'),
                'attr' => array(
                    'data-toggle'=>"tooltip",
                    'data-placement'=>"top",
                    'title'=>"Choisissez la catégorie dans laquelle publier le feedback",
                )))

这首先在保存时给我带来了错误,我必须按如下方式更改 setter :

/**
 * @param \AppBundle\Entity\Social\PostCategory $postCategories
 *
 * @return Post
 */
public function setPostCategories($postCategories)
{
    if (is_array($postCategories) || $postCategories instanceof Collection)
    {
        /** @var PostCategory $postCategory */
        foreach ($postCategories as $postCategory)
        {
            $this->addPostCategory($postCategory);
        }
    }
    else
    {
        $this->addPostCategory($postCategories);
    }

    return $this;
}

/**
 * Add postCategory
 *
 * @param \AppBundle\Entity\Social\PostCategory $postCategory
 *
 * @return Post
 */
public function addPostCategory(\AppBundle\Entity\Social\PostCategory $postCategory)
{
    $postCategory->addPost($this);
    $this->postCategories[] = $postCategory;

    return $this;
}

/**
 * Remove postCategory
 *
 * @param \AppBundle\Entity\Social\PostCategory $postCategory
 */
public function removePostCategory(\AppBundle\Entity\Social\PostCategory $postCategory)
{
    $this->postCategories->removeElement($postCategory);
}

/**
 * Get postCategories
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getPostCategories()
{
    return $this->postCategories;
}
/**
 * Constructor
 * @param null $user
 */
public function __construct($user = null)
{
    $this->postCategories = new \Doctrine\Common\Collections\ArrayCollection();
}

现在,在编辑帖子时,我也遇到了一个问题,因为它使用了一个 getter 来输出一个集合,而不是单个实体,并且我的类别字段未正确填充。

/**
 * Get postCategories
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getPostCategories()
{
    return $this->postCategories;
}

如果我设置 'multiple' => true ,它就可以工作,但我不希望这样,我希望用户只选择一个类别,并且我不想只用断言来限制它。

当然,有些情况下我想让用户选择多个字段,所以我想保留多对多关系。

我能做什么?

最佳答案

如果您想在添加到 ManyToMany 集合时将 multiple 选项设置为 false,您可以在通过创建几个新的 getter 和 setter 并更新表单构建代码来创建实体。

(有趣的是,我在升级到 Symfony 2.7 后才在我的项目中看到这个问题,这迫使我设计这个解决方案。)

这是使用您的实体的示例。该示例假设您需要验证(因为这有点复杂,因此希望这个答案对其他人更有用!)

将以下内容添加到您的 Post 类中:

public function setSingleCategory(PostCategory $category = null)
{
    // When binding invalid data, this may be null
    // But it'll be caught later by the constraint set up in the form builder
    // So that's okay!
    if (!$category) {
        return;
    }

    $this->postCategories->add($category);
}

// Which one should it use for pre-filling the form's default data?
// That's defined by this getter.  I think you probably just want the first?
public function getSingleCategory()
{
    return $this->postCategories->first();
}

现在更改表单中的这一行:

->add('postCategories', 'entity', array(

成为

->add('singleCategory', 'entity', array(
    'constraints' => [
        new NotNull(),
    ],

即我们更改了它引用的字段,还添加了一些内联验证 - 您无法通过注释设置验证,因为您的类上没有名为 singleCategory 的属性,只有一些使用该短语的方法。

关于php - Symfony实体字段: manyToMany with multiple = false - field not populated correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28625891/

相关文章:

php - CakePHP Controller 别名

PHP - 通过一种形式的多个输入上传多个文件

javascript - 如何在同一窗口中显示表单输出并隐藏表单

php - Symfony 5 无法将 EntityManagerInterface 注入(inject)验证器

php - Doctrine2 PostgreSQL 架构限制

php - Doctrine QueryBuilder 未定义方法 getQuery()

php - 尽管上传成功,AFNetworking 2.0 POST + PHP 阻止失败

用于将单个表导出到 SQL 文件的 PHP 脚本

css - 如何在 XHTML 中制作按钮计票

php - Symfony 3 部署到 Azure - 路由问题