如何为所有现有的Symfony3 Type添加自定义'help'选项?
在Symfony2中,我这样做http://toni.uebernickel.info/2012/11/03/how-to-extend-form-fields-in-symfony2.1.html,但现在我升级到Symfony3并且它不再起作用了 - 它给了我“帮助”选项不存在
http://symfony.com/doc/current/form/form_customization.html#adding-help-messages可行,但需要将所有帮助文本移到模板中:
{{ form_widget(form.title, {'help': 'foobar'}) }}
...来自Type类:
->add(
'periodFrom',
TextType::class,
[
'label' => 'period-from',
'required' => false,
'help' => 'period-from.help'
]
)
我想避免这种情况。感谢。
答案 0 :(得分:3)
为此,在此http://symfony.com/doc/current/form/form_customization.html#adding-help-messages之后,您可以创建表单类型扩展名,以便将help
选项传递给所有表单字段:
<?php
// src/AppBundle/Form/Extension/FormTypeExtension.php
namespace AppBundle\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
class FormTypeExtension extends AbstractTypeExtension
{
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['help'] = $options['help'];
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'help' => null,
));
}
public function getExtendedType()
{
return FormType::class;
}
}
现在注册表单类型扩展名:
services:
app.form_type_extension:
class: AppBundle\Form\Extension\FormTypeExtension
tags:
- { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }