HPierce
HPierce

Reputation: 7409

Cannot load Symfony2 form extension

Symfony doesn't seem to load any classes found in AppBundle\Form\Extension while the documentation suggests it should after registering it as a service.

My extension looks like this:

<?php
//src/AppBundle/Form/Extension/FieldTypeExampleExtension.php

namespace AppBundle\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class FieldTypeExampleExtension extends AbstractTypeExtension
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->setAttribute('example', $options['example']);
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['example'] = $options['example'];
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'example' => null,
        ));
    }

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

}

and it is registered as a service like so:

#services.yml
AppBundle.ExampleExtension:
    class: AppBundle\Form\Extension\FieldTypeExampleExtension
    tags:
        - { name: form.type_extension, alias: field }

When I try to utilize this extension, I get the following error:

    $builder->add('city', 'text',array(
        'required' => false,
        //'help is made available by https://github.com/simplethings/SimpleThingsFormExtraBundle
        'help' => 'separate multiple cities with a comma. Example: Chicago, Miami, San Fransisco',
        'example' => 'that those them'
    ))

The option "example" does not exist.

When putting in an obvious syntax error in FieldTypeExampleExtension.php, forms are still rendered without errors, leading me to believe the extension has never been loaded. The Symfony docs and other blog posts suggest that it would be loaded automatically.

Is there a way to force it to load? Or otherwise implement the extension?

Upvotes: 0

Views: 299

Answers (1)

malcolm
malcolm

Reputation: 5542

The alias key of the tag is the type of field that this extension should be applied to.

You not call your extension, only normal 'text' field. Alias is the key, in your example 'field', so you should do:

$builder->add('city', 'field', ......

Or if you want to extend the text field type, you will use 'text' as an alias, and change getExtendedType() function to return 'text'.

Upvotes: 1

Related Questions