This repository aims to provide simple enumeration implementation to Symfony :
$ composer require yokai/enum-bundle<?php
// 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.
<?php
// 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 :
<?php
// 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 :
<?php
// 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)
{
$builder
// Let the bundle guess the form type for you (requires that you configured the validation)
->add('gender')
// 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') }}- Usage in SonataAdminBundle : see doc
- All the ways to declare enums or translated enums
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.



