使用路线链接表格标签

smo*_*ove 6 symfony

在我的注册表单中,我有一个复选框"我接受条款",并希望将"条款"一词链接到我的条款页面.

有没有办法使用路由添加表单标签的链接?(最好不要在表格中注入容器)

Far*_*ona 7

Symfony 5.1 中有新的表单改进。

表单标签中允许包含 HTML 内容!

出于安全原因,默认情况下,表单标签中的 HTML 内容会被转义。新的 label_html 布尔选项允许表单字段在其标签中包含 HTML 内容,这对于在按钮、链接和复选框/单选按钮标签等中显示某些格式很有用。


// src/Form/Type/TaskType.php
namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('save', SubmitType::class, [
                'label' => ' Save',
                'label_html' => true,
            ])
        ;
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您可以直接从模板设置表单标签并将路线传递到那里。

{{ form_widget(form.acceptTermsAndConditions, {
    label: '<a href="' ~ path("route") ~ '">' ~ "I accept ..."|trans ~ '</a>',
    label_html: true
    })
}}
Run Code Online (Sandbox Code Playgroud)


tot*_*tas 6

由于上面的解决方案不适合我,我使用此处建议的解决方案解决了它:https://gist.github.com/marijn/4137467

好的,所以在这里我是如何做到的:

    {% set terms_link %}<a title="{% trans %}Read the General Terms and Conditions{% endtrans %}" href="{{ path('get_general_terms_and_conditions') }}">{% trans %}General Terms and Conditions{% endtrans %}</a>{% endset %}
{% set general_terms_and_conditions %}{{ 'I have read and accept the %general_terms_and_conditions%.'|trans({ '%general_terms_and_conditions%': terms_link })|raw }}{% endset %}
<div>
{{ form_errors(form.acceptGeneralTermsAndConditions) }}

{{ form_widget(form.acceptGeneralTermsAndConditions) }}
<label for="{{ form.acceptGeneralTermsAndConditions.vars.id }}">{{ general_terms_and_conditions|raw }}</label>
</div>
Run Code Online (Sandbox Code Playgroud)


Mae*_*lyn 4

最好的方法是覆盖用于渲染该特定标签的树枝块。

首先,检查文档的表单片段命名部分。然后在表单模板中使用适当的名称创建一个新块。不要忘记告诉 twig 使用它:

{% form_theme form _self %}
Run Code Online (Sandbox Code Playgroud)

对于下一步,请检查默认form_label

您可能只需要其中的一部分,如下所示(我在此处保留默认块名称):

{% block form_label %}
{% spaceless %}
    <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}>
        <a href="{{ path("route_for_terms") }}">{{ label|trans({}, translation_domain) }}</a>
    </label>
{% endspaceless %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

  • 请参阅[如何自定义单个字段](http://symfony.com/doc/current/cookbook/form/form_customization.html#how-to-customize-an-individual-field)。假设您的表单名为 *form*,则块名称将为“_form_termsAccepted_label”。 (3认同)