symfonyphp-5.3sonata-admin

SonataAdmin: generate form fields for enum?


Is there any default way to make Sonata Admin generate form fields for mysql enums as a choice of some sort? Radio buttons, select, whatever, i.e. not a text field where user can enter whatever he wants? It treats them like strings now, rendering input text field.

I have my enums defined this way:

myProperty:
    type: enum
    length: 10
    column: my_property
    columnDefinition: ENUM('yeah', 'whatever')

and they are "real" enums, i.e. my_property column is of mySQL enum type in the database.

I'd prefer a solution that doesn't require me to hardcode enum values into Sonata's Admin.php file, if possible...


Solution

  • I think the best way to do it is using a choice field and you can provide choices with an array that you get from databases.

    Here's an example function for codeIgniter and you can write the same for Symfony2.

    So in your admin class you can add your field to the form like this:

        $formMapper->add('my_property',
                    'choice',
                     array('choices' => MyEnitity::get_enum_values('my_property') );
    

    Make sure to provide keys for the array because sonata will use them as as values.