Search code examples
symfonysymfony5easyadmin

How to use Association field in Symfony EasyAdmin 4


When I use:

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

I get error "Object of class App\Entity\XYZ could not be converted to string"

When I add ->autocomplete() to the AssociationField::new('XYZ'), then it works, but on save it displays error "Expected argument of type "?string", "App\Entity\XYZ" given at property path "XYZ".

Whats the CORRECT way to use this field with many to one relation? Symfony Easy Admin documentation https://symfony.com/doc/current/EasyAdminBundle/fields/AssociationField.html doesn't help at all.


Solution

  • Your entity App\Entity\XYZ will be converted to a string in your association field (which is a standard symfony entity type). Otherwise there is no way to set a label in your entity select.

    It will try to convert it using the __toString method, so you need to add it in your entity.

    For example:

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

    EasyAdmin should be able to guess the entity class, so you don't have to specify it like you would for a simple EntityType.