Simple enumeration system with Symfony integration

v2.2 2018-02-14 10:07 UTC


Latest Stable Version Latest Unstable Version Total Downloads License

Build Status Scrutinizer Code Quality Code Coverage SensioLabsInsight

This repository aims to provide simple enumeration implementation to Symfony :


Add the bundle as dependency with Composer

$ composer require yokai/enum-bundle

Enable the bundle in the kernel

// config/bundles.php

return [
        // ...
    Yokai\EnumBundle\YokaiEnumBundle::class => ['all' => true],


Let's take an example : our application has some members and each member has a gender which can be "male" (m) or "female" (f).

We first need to create the classes that will handle our enums :

Note this example is optimized for latest versions of Symfony, you will find more in dedicated doc file.

// src/App/Enum/GenderEnum.php
namespace App\Enum;

use Yokai\EnumBundle\Enum\EnumInterface;
use Yokai\EnumBundle\Enum\EnumWithClassAsNameTrait;

class GenderEnum implements EnumInterface
    use EnumWithClassAsNameTrait;

    public function getChoices()
        return ['m' => 'Male', 'f' => 'Female'];

If you are using PSR-4 service discovery, then your service is already registered.

That's it, now the bundle know your enum services. You can start using it.

Adding validation to your model :

// src/App/Model/Member.php
namespace App\Model;

use Yokai\EnumBundle\Validator\Constraints\Enum;

class Member
     * @var string
     * @Enum("App\Enum\GenderEnum")
    protected $gender;

Adding enum form types :

// src/App/Form/Type/MemberType.php
namespace App\Form\Type;

use App\Enum\GenderEnum;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
// For Symfony >= 2.8
use Yokai\EnumBundle\Form\Type\EnumType;

class MemberType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)
            // Let the bundle guess the form type for you (requires that you configured the validation)

            // Manual form type binding for Symfony >= 2.8
            ->add('gender', EnumType::class, ['enum' => GenderEnum::class])

            // Manual form type binding for Symfony 2.7
            ->add('gender', 'enum', ['enum' => GenderEnum::class])

Displaying the label for an enum value within a template :

{{ value|enum_label('App\\Enum\\GenderEnum') }}


MIT License

License can be found here.


The bundle was originally created by Yann Eugoné. See the list of contributors.

Thank's to Prestaconcept for supporting this bundle.