2016-07-04 86 views
4

Symfony MoneyType Field呈現爲input type="text",它允許用戶在該字段中輸入他們想要的任何內容。如何重寫Symfony表單MoneyType輸入爲type =「number」?

如何覆蓋此設置以呈現爲input type="number",以便用戶只能輸入數字字符?

$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,所以無法工作。

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

這裏是我的簡單的枝杈:

{{ form_start(form) }} 

    {{ form_widget(form) }} 

    <input type="submit" /> 

{{ form_end(form) }} 

我也很好奇,爲什麼這是默認的輸入類型的錢?我正在考慮擴展或修改類以適應此,但我相信我沒有看到一些優勢。

回答

0

你應該能夠覆蓋默認的字段模板:由

{%- block money_widget -%} 
    <!-- set your custom html input here --> 
{%- endblock money_widget -%} 

{%- block form_widget_simple -%} 
    {%- set type = type|default('text') -%} 
    <input type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/> 
{%- endblock form_widget_simple -%} 

.... other templates .... 

{%- block money_widget -%} 
    {{ money_pattern|replace({ '{{ widget }}': block('form_widget_simple') })|raw }} 
{%- endblock money_widget -%} 

在自定義模板定義

應用程序/資源/視圖/表格/域.html.twig

有關如何覆蓋域模板的詳細信息,請參閱本文檔:

http://symfony.com/doc/current/cookbook/form/form_customization.html#method-2-inside-a-separate-template

2

爲什麼不使用「規模」到指定的小數號碼,也可使用「佔位」告訴用戶的格式爲:

->add('amount', MoneyType::class, array(
     'label' => 'Enter Amount:', 
     'scale' => 2, 
     'attr' => array(
       'placeholder' => 'x.xx', 
     ), 
)) 

我不確定這是否有幫助。

編輯#2。 獲得反饋後,我認爲這應該爲你工作:

use Symfony\Component\Validator\Constraints\Regex; 
... 

->add('amount', MoneyType::class, array(
     'label' => 'Enter Amount:', 
     'scale' => 2, 
     'attr' => array(
       'placeholder' => 'x.xx', 
     ), 
     'constraints' => array(
       new Regex(array('pattern' => '/[0-9]{1,}\.[0-9]{2}/')), 
     ), 
)) 

有關添加驗證此鏈接的信息: http://symfony.com/doc/current/book/forms.html#adding-validation

上述正則表達式指定小數點前至少1程序數字,小數點後2位數字。在你原來的帖子中,你提到'貨幣',但那是一個'字符串'。您可以根據您的需要修改正則表達式。

我還沒有驗證(我使用類似的東西),但我認爲它應該工作。

+0

感謝您的回答,但仍允許人們在鍵入字母字符,而不是隻有數字的。 –

+0

嗨,你能指定你需要的輸入格式嗎?然後我可以給你一個更好的答案。例如,格式爲d.dd,其中'd'是一個十進制值。 –

+0

小數點後兩位很好,這是默認值。我注意到提交,如果它是一個有效的數字,然後它截斷到兩位小數,這是好的。 –

0

我有同樣的問題。當我在Money Type字段中輸入字符串時,我有一個php「數字解析失敗」消息。

爲了解決這個問題,我將php.ini文件中的intl.error_level值修改爲0.您也可以對該行進行註釋。

沒有PHP錯誤了。如果我輸入一個字符串,錯誤由Symfony處理,我只是在我的輸入下顯示消息「這個值無效」。所以沒有必要重寫input type="text"

相關問題