EasyAdmin 3.X - 如何查看相关实体 `toString` 而不是列表中关联的数量?

EasyAdmin 3.X - How to see related entities `toString` instead of the number of association in the list?

我有一个实体 Product 与一个实体 Category

存在多对多关系
/**
 * @ORM\ManyToMany(targetEntity="App\Domain\Category", inversedBy="stalls")
 */
private $categories;

//...

/**
 * @return Collection|Category[]
 */
public function getCategories(): Collection
{
    return $this->categories;
}

ProductCrudControllerclass中我有以下configureFields方法:

public function configureFields(string $pageName): iterable
{
    return [
        Field::new('name'),
        Field::new('description'),
        AssociationField::new('categories'),
    ];
}

当 creating/editing a Product 关系中的一切都按预期工作,但在产品列表中我看到的不是相关类别,而是产品的类别数。我怎样才能改变这种行为?

在下图中,第一个产品有 1 个类别,列表中的第二个产品有 2 个不同的类别。我希望在此处显示类别的名称。

附带说明:Category class 有一个 __toString 方法返回类别的名称。

编辑:

我要查找的行为与下图中的 Tags 列相同:

在 crud 控制器中使用 ArrayField::new('categories'), 而不是 AssociationField::new('categories'),

当creating/editing一个产品现在显示不同,但足够好

您可以使用方法 formatValue 格式化值,如下所示:

->formatValue(function ($value, $entity) {
                $str = $entity->getCategories()[0];
                for ($i = 1; $i < $entity->getCategories()->count(); $i++) {
                    $str = $str . ", " . $entity->getCategories()[$i];
                }
                return $str;
              })

您可以像这样制作一个模板:

// somewhere here templates/admin/field/category.html.twig
{% for category in field.value %}
  {%- set url = ea_url()
    .setController('Path\To\Your\CategoryCrudController')
    .setAction('detail')
    .setEntityId(category.id)
  -%}
  <a href="{{ url }}">
    {{ category.name }}{% if not loop.last %}, {% endif %}
  </a>
{% else %}  
  <span class="badge badge-secondary">None</span>
{% endfor %}

并将其添加到字段中

// in ProductCrudController
AssociationField::new('categories')->setTemplatePath('admin/field/category.html.twig'),

我的详细信息页面上有同样的问题。因此,我没有使用模板,而是根据 pagename

更改字段类型
if (Crud::PAGE_DETAIL === $pageName) {
   $field = ArrayField::new('field')->setLabel('label');
} else {
   $field = AssociationField::new('field')->setLabel('label');
}

我会这样做的:

->formatValue(function ($value, $entity) {
    return implode(",",$entity->getCategories()->toArray());
})