3

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.

Tim
  • 75
  • 1
  • 7
  • Also, how can I show option details (for example id, name etc.)? Right now it displays Position#1, Position#2 etc. which doesn't represent what's inside. – Tim Apr 07 '22 at 11:29

1 Answers1

6

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.

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • You. are. a. wizard. Thank you so much! This should be in the official docs as a base explanation of this field... – Tim Apr 07 '22 at 12:05
  • One more question: can I add a functionality do ADD new record from that field if it doesn't exist? – Tim Apr 07 '22 at 12:10
  • You could create your own field to handle this case, however you cannot do it by configuring your association field. Which is basically just a select of entities (multiple or not) with an optionnal autocomplete. – Dylan KAS Apr 07 '22 at 12:14
  • Understood. How I can enable multiple select? Right now it allows to choose only one position. – Tim Apr 07 '22 at 12:28
  • If you look into `AssociationField` you can see it use `setFormType(EntityType::class)` which mean your field is just an `EntityType`, then you can look into the symfony documentation for this type and look at every options available. In your case you can find `multiple`: https://symfony.com/doc/current/reference/forms/types/entity.html#multiple However it will only work if your property allow multiple values (ManyToMany, OneToMany) – Dylan KAS Apr 07 '22 at 12:55
  • Then you have to use `setFormTypeOption`: `AssociationField::new('XYZ')->setFormTypeOption('multiple', true);` – Dylan KAS Apr 07 '22 at 12:57