使用路径在表单标签中链接

问题描述 投票:0回答:7

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

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

symfony
7个回答
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,
            ])
        ;
    }
}

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

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

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>

4
投票

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

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

{% form_theme form _self %}

对于下一步,请检查 default

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 %}

3
投票

作为一种选择,您可以这样做:

->add('approve', CheckboxType::class, [
    'label' => 'Text part without link',
    'help' => 'And <a href="/x.pdf">download it</a>',
    'help_html' => true,
])

1
投票

我的解决方案是另一个:

形式:

$builder
->add(
    'agree_to_rules',
    'checkbox',
    [
        'required' => true,
        'label' => 'i_agree_to'
    ]
);

和 html:

<span style="display:inline-block">
    {{ form_widget(form.agree_to_rules) }}
</span>
<span style="display:inline-block">
        <a href="#">rules</a>
</span>

而且看起来一样:)


0
投票

我当前的 Symfony v7 注册表。

条款和条件通过

help
属性添加,并将
help_html
设置为
true

Router 被注入到控制器中,因为 Form 是一种服务。

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;

class RegistrationFormType extends AbstractType
{
    public function __construct(
        private readonly RouterInterface $router
    )
    {

    }

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'Name',
                'attr' => [
                    'autofocus' => true,
                    'autocomplete' => 'name',
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                ],

            ])
            ->add('email', EmailType::class, [
                'label' => 'Email',
                'attr' => [
                    'autocomplete' => 'email',
                ],

            ])
            ->add('plainPassword', PasswordType::class, [
                // instead of being set onto the object directly,
                // this is read and encoded in the controller
                'mapped' => false,
                'label' => 'Password',
                'help' => 'Your password should be at least 6 characters long.',
                'attr' => [
                    'autocomplete' => 'new-password'
                ],
                'constraints' => [
                    new NotBlank([
                        'message' => 'Please enter a password',
                    ]),
                    new Length([
                        'min' => 6,
                        'minMessage' => 'Your password should be at least {{ limit }} characters',
                        // max length allowed by Symfony for security reasons
                        'max' => 4096,
                    ]),
                ],
            ])
            ->add('agreeToTerms', CheckboxType::class, [
                'mapped' => false,
                'label' => 'Agree to our terms and conditions',
                'help' => 'View <a href="' . $this->router->generate('app_terms') . '">terms and conditions</a>.',
                'help_html' => true,
                'constraints' => [
                    new IsTrue([
                        'message' => 'You should agree to our terms and conditions.',
                    ]),
                ],
            ])
            ->add('submit', SubmitType::class, [
                'label' => 'Continue',
                'attr' => [
                    'data-variant' => 'primary',
                    'style' => 'width: 100%;'
                ]
            ]);
    }

    public function getBlockPrefix(): string
    {
        return '';
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

-1
投票

一个非常简单的方法是

{{ form_widget(form.terms, { 'label': 'I accept the <a href="'~path('route_to_terms')~'">terms and conditions</a>' }) }}

如果您想使用翻译,也可以这样做

在您的翻译文件中添加例如 messages.en.yml

terms:
    url: 'I accept the <a href="%url%">terms and conditions</a>'

并在您的视图中添加

{{ form_widget(form.terms, { 'label': 'terms.url'|trans({'%url%': path('route_to_terms')}) }) }}
© www.soinside.com 2019 - 2024. All rights reserved.