Search code examples
phpsymfonyeasyadmin

Use a static function to define an array for the choices options of a form


I use the easyAdminBundle, I would like to know if it's possible to use a static function or const (define anywhere in my app) to set the choices option of a choice type as such :

- { property: tag, type: choice, type_options: { choices: 'App\Entity\News::getTags' }

With a getTags function like :

class News 
{
    const TAGS = ['toto','tutu'];

    static public function getTags()
    {
        return $this::TAGS;
    }
}

It is already possible to do that with query_builder but I didn't find any trace of it in the documentation.

Actually I get the following error which lead me to think it's not possible (but maybe someone here do):

An error has occurred resolving the options of the form "Symfony\Component\Form\Extension\Core\Type\ChoiceType": The option "choices" with value "App\Entity\News::getTags" is expected to be of type "null" or "array" or "\Traversable", but is of type "string".


Solution

  • Following the advice of @David Alvarez, I've tried to access the const property directly from the yaml file. This is possible thanks to this symfony update available since the 3.2 version.

    so to access a const property as :

    class News 
    {
        const TAGS = ['toto' => 'toto','tutu' => 'tutu'];
    }
    

    I'll write :

    { choices: !php/const App\Entity\News::TAGS }
    

    and it works like a charm