Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Symfony Form 2.3 in Silex

I'm trying to build a Symfony form (in Silex) by name. Using the configuration below, I believe I should be able to call $form = $app['form.factory']->createBuilder('address');, however the FormRegistry cannot find a form of this type.

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormTypeExtensionInterface;

class AddressType extends AbstractType implements FormTypeExtensionInterface
{
    public function getName()
    {
        return 'address';
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('addressee', 'text');
        // .. fields ..
        $builder->add('country', 'text');
    }

    public function getExtendedType()
    {
        return 'form';
    }
}

This is then added to the form registry using the form.type.extensions provider:

$app['form.type.extensions'] = $app->share($app->extend('form.type.extensions', function($extensions) use ($app) {
    $extensions[] = new AddressType();

    return $extensions;
}));

Is there something else I need to do or a different way of building the form in this way?

like image 958
Ross Avatar asked Feb 17 '23 20:02

Ross


2 Answers

Why not use direct

$app['form.factory']->createBuilder('Namespace\\Form\\Types\\Form')
like image 155
Zlatin Hristov Avatar answered Feb 28 '23 05:02

Zlatin Hristov


First, sorry for my poor english. :)

I think you should extend form.extensions, instead of form.type.extensions.

Something like this:

    $app['form.extensions'] = $app->share($app->extend('form.extensions',
                    function($extensions) use ($app) {
                        $extensions[] = new MyTypesExtension();

                        return $extensions;
                    }));

Then your class MyTypesExtension should look like this:

use Symfony\Component\Form\AbstractExtension;

class MyTypesExtension extends AbstractExtension
{

    protected function loadTypes()
    {
        return array(
            new AddressType(),
            //Others custom types...

        );

    }

}

Now, you can retrieve your custom type this way:

$app['form.factory']->createBuilder('address')->getForm();

Enjoy it!

like image 21
jmpantoja Avatar answered Feb 28 '23 05:02

jmpantoja