Slava Fomin II
Slava Fomin II

Reputation: 28621

Field name from inside a FormType in Symfony2 Forms?

Please look at the example:

/** @var FormBuilderInterface $builder */

$builder->add('foo', new MyFormType());
$builder->add('bar', new MyFormType());
$builder->add('baz', new MyFormType());

I need to get current's field name from inside a MyFormType instance (by the field name i mean: foo, bar and baz from the example above). How can i do this? What method to choose and how can i obtain field's name inside it?

More generally, i need to call some external function with field name as an argument for every form element with specific type, so i decided to do it from inside a FormType class, it looks like good encapsulation.

Upvotes: 0

Views: 119

Answers (1)

Mats Rietdijk
Mats Rietdijk

Reputation: 2576

You can't get the field name asfar as i know, you can get the parent though. From inside the MyFormType buildForm method:

$parent = $builder->getParent();

If i understand your question correct i think the best way to do it is to add a constructor in your MyFormType that accepts a string:

$builder->add('foo', new MyFormType('foo'));

Upvotes: 1

Related Questions