Marius Bogdan
Marius Bogdan

Reputation: 434

Symfony Forms extend FormBuilder

I want to use Symfony Forms in a project and build form classes. If I have a ContactForm class (as example), I would have buildForm method like this:

<?php

...

class ContactType extens AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('first_name', 'text')
            ->add('email', 'email')
        ;
    }
}

What I want to do is to have custom methods for each field type like this:

<?php

...

class ContactType extens AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addText('first_name')
            ->addEmail('email')
        ;
    }
}

Anyone has any idea how can I extend the $builder ? Thank you

Upvotes: 2

Views: 520

Answers (1)

Marcos Segovia
Marcos Segovia

Reputation: 94

Have you tried in making your own Class by customizing the usage of the FormBuilderInterface?

I mean, for example:

use Symfony\Component\Form\FormBuilderInterface;

class MyFormBuilderInterface extends AbstractType
{
    private $builder;

    function __construct(FormBuilderInterface $builder)
    {
        $this->builder = $builder;
    }
    private function addText($input)
    {
        $this->builder->add('first_name', 'text');
    }

    private function addEmail($input)
    {
        $this->builder->add('email', 'email');
    }
}

Upvotes: 3

Related Questions