dongnue4923 2016-10-09 14:45
浏览 74
已采纳

向Symfony 3添加所有表单类型的帮助选项

How could I add custom 'help' option to all existing Symfony3 Type's?

In Symfony2, I did it like this http://toni.uebernickel.info/2012/11/03/how-to-extend-form-fields-in-symfony2.1.html but now I'm upgrading to Symfony3 and it does not work any more - it gives me The option "help" does not exist.

http://symfony.com/doc/current/form/form_customization.html#adding-help-messages would work, but it would require to move all help texts into template:

{{ form_widget(form.title, {'help': 'foobar'}) }}

...from Type classes:

->add(
    'periodFrom',
    TextType::class,
    [
        'label' => 'period-from',
        'required' => false,
        'help' => 'period-from.help'
    ]
)

I'd like to avoid that. Thanks.

  • 写回答

1条回答 默认 最新

  • doushi9376 2016-10-10 00:35
    关注

    To do that and after this http://symfony.com/doc/current/form/form_customization.html#adding-help-messages you can create a form type extension to pass help option to all form fields:

    <?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;
        }
    }
    

    Now register the form type extension:

    services:
        app.form_type_extension:
            class: AppBundle\Form\Extension\FormTypeExtension
            tags:
                - { name: form.type_extension, extended_type: Symfony\Component\Form\Extension\Core\Type\FormType }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题