steevanb/symfony-form-options-builder

buildForm() with objects instead of array

4.4.1 2023-07-31 08:54 UTC

README

version php symfony Lines Total Downloads Scrutinizer

symfony-form-options-builder

It helps you writing your Symfony FormType, with some traits and methods to add fields in buildForm() instead of array with some mysterious keys, and other stuff.

Installation

Changelog

Object-oriented FormType

FormType::buildForm() object oriented instead of array

Example:

namespace FooBundle\Form\Type;

use Steevanb\SymfonyFormOptionsBuilder\OptionsBuilder\EmailOptionsBuilder;
use Steevanb\SymfonyFormOptionsBuilder\OptionsBuilder\TextOptionsBuilder;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class BarType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        # Since PHP 5.5, you can use FooClass::class
        $builder->add('field_text', TextType::class, TextOptionsBuilder::create()->asArray());

        # Since PHP 5.6, you can use the variadic syntax. asVariadic() parameter is field name.
        $builder->add(
            ...EmailOptionsBuilder::create()
                ->setRequired(false)
                ->setPlaceHolder('default@mail.com')
                ->setTrim(false)
                ->asVariadic('field_email')
        );
    }
}

More documentation

BlockPrefixTrait

Add getBlockPrefix(), to always return same syntax for form type getBlockPrefix() method: form_type_formtypeclassname

Example:

namespace FooBundle\Form\Type;

use Steevanb\SymfonyFormOptionsBuilder\BlockPrefixTrait;

class BarType extends AbstractType
{
    # Use this trait to define getBlockPrefix() required method. It will return form_type_bar
    use BlockPrefixTrait;
}