【问题标题】:Symfony buildForm: place checkbox input inside label tagsSymfony buildForm:将复选框输入放在标签标签内
【发布时间】:2021-09-27 02:22:57
【问题描述】:

我在 symfony 5.3 中有一个用 buildForm 制作的表单

其中一个表单字段是复选框,即“活动”字段。这是代码:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // some other fields
        ->add('active')
    ;
}

formBuilder 正在打印这样的复选框:

<div>
    <label for="extract_ac_configuration_active">Active</label>
    <input type="checkbox" id="extract_ac_configuration_active" name="extract_ac_configuration[active]" value="1">
</div>

但是因为我希望标签不需要javascript就可以点击,并且因为我使用的css框架,我需要将它呈现为

<label>
    <input type="checkbox" id="extract_ac_configuration_active" name="extract_ac_configuration">
    <span>active</span>
</label>

如何将复选框通过 buildForm 呈现的方式更改为我需要的方式?

【问题讨论】:

  • 如何渲染该字段?使用{{ form_row() }} ?
  • 在控制器$this-&gt;renderForm('route_to/edit.html.twig', [ 'extract_ac_configuration' =&gt; $extractAcConfiguration, 'form' =&gt; $form, ]); 和form.html.twig 中{{ form_widget(form) }} 是您创建php bin/console generate:doctrine:crud 时的默认方式
  • 好的,那么你必须分解表单的渲染。检查我将发布的答案。

标签: symfony symfony-forms formbuilder symfony5


【解决方案1】:

如果你想得到这个结果:

<label>
    <input type="checkbox" id="extract_ac_configuration_active" name="extract_ac_configuration">
    <span>active</span>
</label>

您必须分解表单渲染。而不是像这样全局渲染:

{{ form_widget(form) }}

你必须这样做:

{{ form_start(form) }}

<label>
    {{ form_widget(form.active) }}
    <span>active</span>
</label>

{{ form_end(form) }}

【讨论】:

  • 很好,它有效,谢谢。但只有一个细节。现在复选框呈现为第一个字段,我希望它是最后一个,或者至少在它之前的位置。
  • 为此,我认为您必须手动一一手动渲染其他字段。就像你对活跃领域所做的那样。请注意{{ form_label(form.field) }} 将打印标签,而{{ form_widget(form.field) }} 将打印输入。
  • 是的,我意识到我应该使用{{ form_row(form.field) }}一一渲染所有字段,然后一切都会在这个地方。我必须再次感谢你。我刚刚找到了解释它的文档:symfony.com/doc/current/form/form_customization.html
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多