I’m getting some troubles understanding how Symfony2 custom form field types work. I need to create a new type with some custom attributes (HTML5 data-*) based on data passed to MyType.
The problem is that after adding MyType to the main form, its label inherits the data-* attribute.
// Add MyType to the main form
$builder->add('somename', new MyType(), array('label' => 'my label'));
This is my custom type:
class MyType extends AbstractType
{
public function getDefaultOptions(array $options)
{
$source = isset($option['source']) ? json_encode($option['source']) : '';
return array(
'attr' => array(
'data-source' => $source
)
);
}
public function getName() { return 'mytype'; }
public function getParent(array $options) { return 'text'; }
}
EDIT: as far as i can understand passing
array('attr' => array('myattr1' => 'value1'))as option for the builder is intended as common attributes for the builder and all its child elements. This is why, for example, passingarray('required' => false)at form level will disable HTML5 built-in client side validation for each field inside that form.(Always looking for a better solution) i’ll post my way, inspired by this blog post: a custom form field with view attributes and a Twig block to create new attributes.
The new form type should be register as a service and alias should match what’s being returned by
getName()(is this mandatory? dunno…):New field creation (elsewhere):
In Twig form theme widget block (pattern for name is
as getName() . '_widget) you can use view attributes setted inTypeheadType:And, finally: