如何在 Symfony EasyAdmin 4 中使用关联字段

Tim*_*Tim 3 symfony easyadmin symfony5

当我使用时:

public function configureFields(string $pageName): iterable
    {
      return [
            AssociationField::new('XYZ')
        ];
    }`
Run Code Online (Sandbox Code Playgroud)

我收到错误"Object of class App\Entity\XYZ could not be converted to string"

当我添加->autocomplete()到 时AssociationField::new('XYZ'),它可以工作,但在保存时显示错误"Expected argument of type "?string", "App\Entity\XYZ" given at property path "XYZ".

使用该字段进行多对一关系的正确方法是什么?Symfony Easy Admin 文档https://symfony.com/doc/current/EasyAdminBundle/fields/AssociationField.html根本没有帮助。

Dyl*_*Kas 6

您的实体App\Entity\XYZ将转换为关联字段中的字符串(这是标准的 symfony 实体类型)。否则无法在实体选择中设置标签。

它将尝试使用__toString方法对其进行转换,因此您需要将其添加到您的实体中。

例如:

/**
 * @ORM\Entity(repositoryClass=XyzRepository::class)
 */
class Xyz
{
  public function __toString(){
    return $this->name; //or anything else
  }
Run Code Online (Sandbox Code Playgroud)

EasyAdmin 应该能够猜测实体类,因此您不必像简单的EntityType.