skip to Main Content

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 AppEntity;

enum OGTypeStatus: string {

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

// inside class
#[ORMColumn(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 AppEntityOGTypeStatus to property AppEntitySEO::$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?

2

Answers


  1. Chosen as BEST ANSWER

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

    #[ORMColumn(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.


  2. Thanks to OP – posting my implementation as an alternate approach

    enum

    enum Color: string
    {
        case Black = 'Black';
        // etc
        case Yellow = 'Yellow';
    }
    

    Use in entity

    #[ORMColumn(length: 16, nullable: true, enumType: Color::class)]
    private ?string $color = null;
    

    In CRUD controller

    public function configureFields(string $pageName): iterable {
        
        return [
            IdField::new('id')->hideWhenCreating(),
            TextField::new('serialNumber'),
            TextField::new('brand'),
            TextField::new('model'),
            IntegerField::new('speeds'),
            NumberField::new('wheelSize'),
            ChoiceField::new('color')->setChoices(Color::cases())->autocomplete(),
      ];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search