mathieu-ducrot / enum-bundle

Enumeration system for Symfony (form, validator, twig)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

YokaiEnumBundle

Latest Stable Version Latest Unstable Version Total Downloads License

This repository aims to provide simple enumeration implementation to Symfony.

Installation

Add the bundle as a dependency with Composer

$ composer require yokai/enum-bundle

Enable the bundle in the kernel

<?php
return [
    Yokai\EnumBundle\YokaiEnumBundle::class => ['all' => true],
];

Usage

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') }}

Recipes

MIT License

License can be found here.

Authors

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


Thank's to Prestaconcept for supporting this bundle.

About

Enumeration system for Symfony (form, validator, twig)

License:MIT License


Languages

Language:PHP 100.0%