18

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?

Ofershap
  • 687
  • 2
  • 7
  • 22

4 Answers4

48

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)?>
Touqeer Shafi
  • 5,084
  • 3
  • 28
  • 45
5

Try this . it worked for me

<?= $form->field($model, 'amount')->textInput(['type' => 'number']) ?>
Shuhad zaman
  • 3,156
  • 32
  • 32
  • 2
    Can also be good to specifict the `min`, `max` and `step` value. `= $form->field($model, 'position')->input('number', ['min' => 0, 'max' => 10000, 'step' => 1]) ?>` – johnsnails Apr 04 '20 at 11:13
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.'], 

...
          ];
}
Manoj Roy
  • 317
  • 2
  • 6
0
<?= $form->field($model, 'code')->textInput(['type'=>'number']) ?>