Sudhakar Krishnan
Sudhakar Krishnan

Reputation: 880

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?

Upvotes: 1

Views: 1347

Answers (2)

user2182349
user2182349

Reputation: 9782

Thanks to OP - posting my implementation as an alternate approach

enum

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

Use in entity

#[ORM\Column(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(),
  ];
}

Upvotes: 0

Sudhakar Krishnan
Sudhakar Krishnan

Reputation: 880

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.

Upvotes: 1

Related Questions