Mike
Mike

Reputation: 12819

Add Entity field type to form with event subscriber class

I am doing something very similar to this cookbook example http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html#adding-an-event-subscriber-to-a-form-class

The main difference is that my field type is an entity and not a text type.

So my field subscriber preSetData method looks like this:

public function preSetData(DataEvent $event)
{
    $data = $event->getData();
    $form = $event->getForm();

    if (null === $data) {
        return;
    }

    if(!$data->getIsCategorized()){

        $form->add(

            $this->factory->createNamed('categories', 'entity', array(
            'class' => 'My\PostBundle\Entity\Category',
            'property'     => 'name',
            'multiple'     => true,
            'label' => 'Category'
            )
            )
        );
    }
}

This is giving the following error

Class does not exist
500 Internal Server Error - ReflectionException 

If I add the entity directly in my form type with $builder->add('categories, 'entity', array(... it works fine

Is it possible to attach an entity field type to a form using a field event subscriber in this fashion?

Upvotes: 1

Views: 1305

Answers (2)

Julien
Julien

Reputation: 9432

I ran into the same problem, and actually it's because the factory->createNamed() method has more argument than the builder->add The third argument isn't the options array, but a "data" argument.

So here's what you should do :

    $form->add(

        $this->factory->createNamed('categories', 'entity', null, array(
        'class' => 'My\PostBundle\Entity\Category',
        'property'     => 'name',
        'multiple'     => true,
        'label' => 'Category'
        )
        )
    );

(add null before the options array)

Upvotes: 1

Bernhard Schussek
Bernhard Schussek

Reputation: 4841

Whether you attach a field in the type or by means of an event listener/subscriber should make no difference. Either you have a small mistake somewhere (likely), or that's a bug, in which case you should submit it to the issue tracker.

Upvotes: 0

Related Questions