3

我有一个非常基本的 symfony 5 + easyadmin 3 应用程序。我使用 make:entity 创建了两个实体:帖子和类别

当我尝试编辑类别以分配帖子时,帖子未保存在数据库中。但是,如果我在帖子编辑中添加类别,则会保存在 db 中。

知道我在这里缺少什么吗?

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;
}
4

1 回答 1

11

由于找到了解决方案: 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();
于 2021-03-21T03:43:54.563 回答