Symfony 的 BirthdayType 字段:如何为生成的文本小部件添加标签?

Symfony's BirthdayType field: how to add labels to generated text widget?

我的 Symfony 表单使用 BirthdayType field. Its default behaviour is to add three separate dropdowns for the month, day and year. I added the text widget option as described here 以便拥有三个独立的文本输入字段。我的问题是:如何为每个输入字段生成标签?

生成的HTML是:

   <div id="user_birthDate">
       <input type="text" id="user_birthDate_month" name="user[birthDate][month]" required="required">
       <input type="text" id="user_birthDate_day" name="user[birthDate][day]" required="required">
       <input type="text" id="user_birthDate_year" name="user[birthDate][year]" required="required">
   </div>

FormBuilder(摘录):

 public function buildForm(FormBuilderInterface $builder, array $options): void
 {
     $builder
        ->add('birthDate', BirthdayType::class, ['widget' => 'text'])
        ->add('next', SubmitType::class);
  }

您可以像使用 'widget'

一样在选项中添加标签
public function buildForm(FormBuilderInterface $builder, array $options): void
 {
 $builder
    ->add('birthDate', BirthdayType::class, [
         'widget' => 'text',
         'label' => 'Birthday label that you want to show',
        ])
    ->add('next', SubmitType::class);
 }

另见 https://symfony.com/doc/current/forms.html#field-type-options

你应该制作一个自定义树枝:

{#birthdate.html.twig !#}

{% block birthday_widget %}
    {% spaceless %}
     <label> month </label>
     <input type="text" id="user_birthDate_month" name="user[birthDate][month]" required="required">

     <label> day </label>
     <input type="text" id="user_birthDate_day" name="user[birthDate][day]" required="required">

     <label> year </label>
     <input type="text" id="user_birthDate_year" name="user[birthDate][year]" required="required">

    {% endspaceless %}
{% endblock %}

并在 config.yml 中添加这一行:

# app/config/config.yml
twig:
    form_themes:
        - 'form/birdhdate.html.twig'