我们可以从Symfony控制器中定义窗体中窗口小部件的id属性吗?

时间:2017-08-30 14:23:13

标签: php forms symfony

我想使用id attribute在表单中定义小部件的form class

从Twig视图中,the Symfony documentation向我们展示了如何添加" foo" class属性:

{{ form_widget(form.surname, {'attr': {'class': 'foo'}}) }}

可以使用以下命令从表单类中完成:

$builder->add('surname', TextType::class, [
    'attr' => ['class' => 'foo'],
])

因此,如果我们可以像这样更改类属性,我们可以假设我们可以更改id属性,如下所示:

{{ form_widget(form.title, { 'attr': {'id': 'my_custom_id'} }) }}

但是这不起作用,我们需要在attr数组之外定义id,如下所示:

{{ form_widget(form.surname, { 'id': 'my_custom_id' }) }}

基于该观察结果,如果我尝试从表单类中定义attr之外的id,如下所示:

$builder->add('surname', TextType::class, [
    'id' => 'my_custom_id',
])

但这是不允许的,我得到以下内容:

  

选项" id"不存在。定义的选项包括:"操作"," allow_extra_fields"," attr"," auto_initialize"," block_name",& #34; by_reference","复合","约束"," csrf_field_name"," csrf_message"," csrf_protection&# 34;," csrf_token_id"," csrf_token_manager","数据"," data_class","禁用",&# 34; empty_data"," error_bubbling"," error_mapping"," extra_fields_message"," inherit_data"," invalid_message&#34 ;," invalid_message_parameters"," label"," label_attr"," label_format"," mapped",&#34 ;方法"," post_max_size_message"," property_path"," required"," translation_domain"," trim" ," upload_max_size_message"," validation_groups"。

我注意到我们无法在widgetattr数组中定义id,而我们可以在label_attr数组内为label执行此操作即使是来自表单类。

是否可以从表单类定义窗口小部件的id?如果是的话,该怎么做?

编辑:我想提一下,我测试了以下内容,只更改了标签的ID。

->add('surname', TextType::class, [
    'label_attr' => ['id' => 'my_custom_id1'],
    'attr' => ['id' => 'my_custom_id2'],
])

我正在使用Symfony v3.3.6

EDIT2:我创建了a sandbox project that reproduces the issue

2 个答案:

答案 0 :(得分:1)

事实上,它是不可能作为Symfony generates ids for form types it renders

此外,这是unlikely to change in the core as that would also be a huge BC break to not generate it anymore

我们只能通过覆盖$view->vars['id']来更改ID的前缀,如下所示:

public function buildView(FormView $view, FormInterface $form, array $options)
{

    $view->vars['id'] = 'myprefix';
}

后缀是$builder->add('surname', TextType::class)中定义的名称。在这种情况下,新ID将为myprefix_surname

答案 1 :(得分:0)

也许您可以使用data-id代替:

$builder
    ->add('surname', TextType::class, array(
            'label' => 'Label:',
            'label_attr' => array(
                    'id' => 'custom_id1',
            ),
            'attr' => array(
                    'data-id' => 'custom_id2',
                    'class' => 'custom_id2',
            ),
    ))
;

我有一个similar problem with the ChoiceType,所以我想知道data-id是否适合你?