This repository aims to provide simple enumeration implementation to Symfony.
$ composer require yokai/enum-bundle
<?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 :
<?php
declare(strict_types=1);
namespace App\Enum;
use Yokai\EnumBundle\EnumInterface;
use Yokai\EnumBundle\EnumWithClassAsNameTrait;
class GenderEnum implements EnumInterface
{
use EnumWithClassAsNameTrait;
public function getChoices(): array
{
return ['m' => 'Male', 'f' => 'Female'];
}
}
If you are using PSR-4 service discovery (or Symfony default services file), then your service is already registered.
That's it, now the bundle know your enum services. You can start using it.
Add validation to any model :
<?php
declare(strict_types=1);
namespace App\Model;
use App\Enum\GenderEnum;
use Yokai\EnumBundle\Validator\Constraints\Enum;
class Member
{
/**
* @Enum(GenderEnum::class)
*/
public ?string $gender = null;
}
Add enumerated form fields to any form :
<?php
declare(strict_types=1);
namespace App\Form\Type;
use App\Model\Member;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class MemberType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
// The bundle will find out the form type for you (thanks to the Enum constraint we added to model)
->add('gender')
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefault('data_class', Member::class);
}
}
Display label of any enum value within a Twig 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.