yii2 ActiveForm numeric textfield
Asked Answered
G

4

20

I've created an ActiveForm using yii2 like this:

                            <?=$form->field($item, 'finalPrice', [
                                'options' => [
                                    'tag' => 'div',
                                    'class' => '',
                                ],
                                'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
                            ])->textInput([
                                 // ** i want numeric value **
                            ])->label(false)?>

and it rendered a result of:

<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label><input type="text" id="item-finalprice" class="form-control" name="Item[finalPrice]"><p class="help-block help-block-error"></p></span>

now i want to make it < input type="number" .. and not text.. (so user could change value using browser up/down buttons). is there any way to do it?

Glasgow answered 9/11, 2015 at 12:35 Comment(0)
P
50

You can use ->textInput(['type' => 'number'] eg :

<?=$form->field($item, 'finalPrice', [
                                'options' => [
                                    'tag' => 'div',
                                    'class' => '',
                                ],
                                'template' => '<span class="col-md-2 col-lg-2"><label class="control-label">Final item price</label>{input}{error}</span>'
                            ])->textInput([
                                 'type' => 'number'
                            ])->label(false)?>
Peppie answered 9/11, 2015 at 12:51 Comment(1)
this what i want to achieveIcsh
S
7

Try this . it worked for me

<?= $form->field($model, 'amount')->textInput(['type' => 'number']) ?>
Scoff answered 28/1, 2019 at 8:12 Comment(1)
Can also be good to specifict the min, max and step value. <?= $form->field($model, 'position')->input('number', ['min' => 0, 'max' => 10000, 'step' => 1]) ?>Cuyler
P
1
<?= $form->field($model, 'code')->textInput(['type'=>'number']) ?>
Partan answered 11/3, 2021 at 9:28 Comment(2)
@WaiHaLee: There’s no link in this answer.Morpho
this is just a copy paste of another answer here.Scoff
N
0

Field like Phone Number/Membership No etc, some time we allow user only to enter numeric input in a text field. In such case applying pattern match rule work great for me.

Simply set a rule in the model class and you are done.

public function rules()
{
    return [
...

 [['contactno'], 'string', 'max' => 25],
 [['contactno'], 'match' ,'pattern'=>'/^[0-9]+$/u', 'message'=> 'Contact No can Contain only numeric characters.'], 

...
          ];
}
Necaise answered 20/3, 2020 at 6:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.