How to override Symfony form MoneyType input as type=“number”?

前端 未结 4 912
天命终不由人
天命终不由人 2021-01-18 09:54

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 ren

4条回答
  •  萌比男神i
    2021-01-18 10:44

    Why not use 'scale' to specify the number of decimal places, and also use 'placeholder' to tell the user the format:

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

    I'm not sure if this is helpful or not.

    Edit #2. After getting feedback, i think this should work for you:

    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}/')),
            ),
    ))
    

    See this link for info on adding Validation: http://symfony.com/doc/current/book/forms.html#adding-validation

    The above regular expression specifies at least 1 proceeding digit before the decimal, and 2 digits following the decimal place. In your original post you referred to 'currency', but that is a 'string'. You can modify the regular expression based on your needs.

    I haven't verified this (I use something similar), but I think it should work.

提交回复
热议问题