Symfony 5 easyadmin 3关联ManyToOne实体-“多”侧不保存

3

我有一个非常基础的Symfony 5 + EasyAdmin 3应用程序。

我使用make:entity创建了两个实体:帖子和类别。

当我尝试编辑类别以分配帖子时,帖子不会保存到数据库中。

但是,如果我在帖子编辑中添加类别,则它会保存到数据库中。

你有什么想法吗?我这里有CategoryCrudController.php

public function configureFields(string $pageName): iterable
{
    if (Crud::PAGE_EDIT === $pageName)
    {
        yield TextField::new('title');
        
        yield DateTimeField::new('created_at')
            ->setFormTypeOption('disabled','disabled');
       
        yield AssociationField::new('posts')
            ->autocomplete();

实体类别.php

/**
 * @ORM\OneToMany(targetEntity=Post::class, mappedBy="category")
 */
private $posts;

public function __construct()
{
    $this->posts = new ArrayCollection();
}


/**
 * @return Collection|Post[]
 */
public function getPosts(): Collection
{
    return $this->posts;
}

public function addPost(Post $post): self
{
    if (!$this->posts->contains($post)) {
        $this->posts[] = $post;
        $post->setCategory($this);
    }

    return $this;
}

public function removePost(Post $post): self
{
    if ($this->posts->removeElement($post)) {
        // set the owning side to null (unless already changed)
        if ($post->getCategory() === $this) {
            $post->setCategory(null);
        }
    }

    return $this;
}

你说得对,这只是一个复制/粘贴错误,因为我编辑了我的代码中的名称,以使其更易理解。无论如何,我非常感谢你抽出时间来回答我的问题。我已经编辑了我的问题。 - Cedric
我认为另一个问题的这个答案是相关的。https://dev59.com/qWox5IYBdhLWcg3wmFWV#35765987 我使用make:entity创建了一个复数的关系字段,我认为这就是问题所在。使用“posts”ManyToOne类别。 - Cedric
1个回答

16

感谢以下链接提供的解决方案: https://github.com/EasyCorp/EasyAdminBundle/issues/860#issuecomment-192605475

对于 Easy Admin 3,您只需要添加:

->setFormTypeOptions([
    'by_reference' => false,
])

CategoryCrudController.php

public function configureFields(string $pageName): iterable
    {
        if (Crud::PAGE_EDIT === $pageName)
        {
            yield TextField::new('title');

            yield DateTimeField::new('created_at')
                ->setFormTypeOption('disabled','disabled');

            yield AssociationField::new('posts')
                ->setFormTypeOptions([
                    'by_reference' => false,
                ])
                ->autocomplete();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接