symfonyeasyadmin

Symfony Easyadmin ChoiceField with enum not working


Symfony Easyadmin throws error while trying to add choice with enum as per official doc EasyAdmin Choice Field.

NOTE:- Unnecessary lines of codes are omitted.

My code:

<?php

namespace App\Entity;

enum OGTypeStatus: string {

    case Website = 'website';
    case Article = 'article';
    case Book = 'book';
    case Profile = 'profile';
}

// inside class
#[ORM\Column(type: Types::STRING, enumType: OGTypeStatus::class, nullable: true)]
private ?string $ogType = null;

In Easyadmin: as per official doc setChoices

// there's no need to call ->setChoices(); EasyAdmin will get all possible
// values via Doctrine; it's equivalent to calling: ->setChoices(BlogPostStatus::cases())
// yield ChoiceField::new('status');

public function configureFields(string $pageName): iterable {
  $ogType = ChoiceField::new('ogType');
  // if(true){ return $ogType}
}

ERROR:- If the value(only for enum field) is already set The error is thrown in Index page and Detail page

Cannot assign App\Entity\OGTypeStatus to property App\Entity\SEO::$ogType of type ?string

If the enum field is empty or null. It displays correctly.

IN NEW page:- when submit with enum value throws error

Warning: Attempt to read property "value" on string

//from log
Uncaught PHP Exception ErrorException: "Warning: Attempt to read property "value" on string" at /home/.../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ReflectionEnumProperty.php line 62

{
    "exception": {}
}

Question:- How to properly set enum in choice field?


Solution

  • Finally it worked by removing enumType: OGTypeStatus::class from entity

    #[ORM\Column(type: Types::STRING, nullable: true)]
    private ?string $ogType = null;
    

    and add choice in easyadmin,

    $ogType = ChoiceField::new('ogType')->setChoices(OGTypeStatus::cases())
    

    all the other lines of code are same.