I would like to do something like this:
$builder->add('firstname', 'text', array(
'myCustomOption' => 'optionValue'
));
so I can use myCustomOption
in myForm.html.twig like this:
{% block form_row -%}
{{ myCustomOption }}
{%- endblock form_row %}
But in this case I get:
The option "myCustomOption" does not exist. Known options are: [..]
This is the answer: Type Extension
It allow to extend desired form type email/phone/checkbox
or group text/entity/choice
or even all available form
. (Remember that one element can contain few types. For example input email
will be type of form, text, email
)
Just create extension class:
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TextTypeExtension extends AbstractTypeExtension {
public function getExtendedType() {
return 'form'; // What type should be extended
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
// Add optional option - you can also add required options
// and available values of this option
$resolver->setOptional(array('myOption'));
}
public function buildView(FormView $view, FormInterface $form, array $options) {
// You can put any logic here
// For example 'myOption' => 'big' can be transformed to
// 'myOption' => '300px'
if (array_key_exists('myOption', $options)) {
// Add your option to twig template
$view->vars['myOption'] = $options['myOption'];
}
}
}
add class as service:
services:
acme_demo_bundle.image_type_extension:
class: Acme\DemoBundle\Form\Extension\TextTypeExtension
tags:
- { name: form.type_extension, alias: form }
and now you can do:
$builder->add('MyInput', 'text', array('myOption' => array('whateverYouNeed')));
Source: http://symfony.com/doc/current/cookbook/form/create_form_type_extension.html
Try something like this:
class MyTextType extends AbstractType
{
public function getParent()
{
return 'text';
}
public function getName()
{
return 'my_text';
}
....
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults([
'myOption' => null
])
;
}
....
}
service definition:
acme_demo_bundle.text_type:
class: Acme\DemoBundle\Form\Type\MyTextType
tags:
- { name: form.type, alias: my_text }
usage:
$builder->add('someName', 'my_text', ['myOption' => $value])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.