【问题标题】:TWIG form template: call variable in attrTWIG 表单模板:在 attr 中调用变量
【发布时间】:2020-08-05 23:16:10
【问题描述】:

在 Symfony 4 应用程序的树枝表单模板中,我需要一个带有变量的属性。

示例:

{{ form_widget(myform.field, {'attr': {'class': 'bidding-slider','data-slider-value': '800'}}) }}

我需要在 'data-slider-value' 中放置一个变量,而不是手动值。

我试过了:

{{ form_widget(myform.field, {'attr': {'class': 'bidding-slider','data-slider-value': '{{ variable }}'}}) }}

但它不起作用......

{{ variable }} 单独返回我需要放入“data-slider-value”的值。

第二次尝试:

我有扩展表单类 'TextType' 方法 buildView。 为此,我添加了这个文件:src/Form/Extension/TextTypeExtension.php

// src/Form/Extension/TextTypeExtension.php
namespace App\Form\Extension;

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FileType;

    class TextTypeExtension extends AbstractTypeExtension
{
    /**
     * Return the class of the type being extended.
     */
    public static function getExtendedTypes(): iterable
    {
        // return FormType::class to modify (nearly) every field in the system
        return [TextType::class];
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
    $tjm = $form->get('dailyrate')->getData();
    $view->vars['attr']['data-slider-value'] = $tjm;
    }
}

但现在我不确定如何在我的表单模板中使用它...

非常感谢你帮助我。

亚历克斯

【问题讨论】:

    标签: twig symfony4 attr


    【解决方案1】:

    扩展表单的类方法buildView:

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['attr']['data-slider-value'] = ...// 
    }
    

    【讨论】:

    • 感谢您的建议 :) 我用我所做的更新了我的初始帖子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多