如何覆盖Symfony形式的MoneyType输入为type =“ number”? [英] How to override Symfony form MoneyType input as type="number"?

查看:152
本文介绍了如何覆盖Symfony形式的MoneyType输入为type =“ number”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Symfony MoneyType字段呈现为 input type = text ,它允许用户在字段中键入他们想要的任何内容。

The Symfony MoneyType Field renders as input type="text" which allows a user to type whatever they want into the field.

如何覆盖此内容以进行渲染作为输入类型=数字 ,以便用户只能输入数字字符?

How can I override this to render as input type="number" so that users can only enter numeric characters?

$formBuilder->add("amount", MoneyType::class, [
  'currency' => 'USD'
]);

当前输出:

<div><label for="form_amount" class="required">Amount</label>$ <input type="text" id="form_amount" name="form[amount]" required="required"  /></div>

我要实现的目标:

<div><label for="form_amount" class="required">Amount</label>$ <input type="number" id="form_amount" name="form[amount]" required="required"  /></div>

我试图简单地覆盖属性类型,但是所有这些都做到了在末尾添加了第二个 type 属性,该属性不起作用,因为它显然是无效的HTML。

I tried to simply override the attribute type, but all this did was add a second type attribute at the end, which didn't work because it's obviously invalid HTML.

$formBuilder->add("amount", MoneyType::class, [
  'attr' => [
    'type' => 'number',
  ],
  'currency' => 'USD'
]);

这是我简单的树枝:

{{ form_start(form) }}

    {{ form_widget(form) }}

    <input type="submit" />

{{ form_end(form) }}






我也很好奇,为什么这是Money的默认输入类型?我正在考虑扩展或修改类以适应这种情况,但是我敢肯定有一些优势我没看到。


I'm also curious, why is this the default input type for Money? I'm considering extending or modifying the class to accommodate this, but I'm sure there's some advantage I'm not seeing.

推荐答案

您可以自定义MoneyType的呈现方式。

You can customise how the MoneyType is rendered.

{% extends 'form_div_layout.html.twig' %}

{% block money_widget %}
    {%- set type = type|default('number') -%}
    {{ parent() }}
{% endblock %}

来源:

http://symfony.com/doc/current/form/form_customization.html#method-2-inside-a-separate-template
https://github.com/symfon y / symfony / issues / 22937#issuecomment-304609466

这篇关于如何覆盖Symfony形式的MoneyType输入为type =“ number”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆