Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2. Form get Input Id

I am trying to the ID of a field in order to use it in js. I have read Yii2 documentation and found ActiveField has a method "getInputId", but how do I call it?

<?php $form = ActiveForm::begin(); ?>
        <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?php $form->end(); ?>

I can save the result from $form->field in a var, but it is a string so not possible to use it that way.

I have been checking ActiveForm code and I see it exists 2 methods: beginField and endField, maybe soemthing to do with that? any ideas will be appreciated.

like image 810
Eduardo Avatar asked Nov 29 '22 09:11

Eduardo


2 Answers

I have found a good solution. There is a method "getInputId" from Html helper. My original question is pending yet. How to use the method "getInputId" from activeField?

<?= Html::getInputId($model, 'phone'); ?>
like image 70
Eduardo Avatar answered Dec 06 '22 08:12

Eduardo


By Default the id for he field is $model-$attribute i.e

if you are using User model and username filed in the form i.e

<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>

The id will be user-username

You can also specify the id manually for the field i.e.

<?= $form->field($model, 'username')->textInput(['maxlength' => true, 'id' => 'my_id']) ?>

in this case the id for the input will be my_id

Edit as per latest comment: (I have not tried this, but explained as per documentation)

as textInput function is return $this http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#textInput()-detail

So getInputId (http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#getInputId()-detail)must be call able as

<?php
 $form->field($model, 'username')->textInput(['maxlength' => true])->getInputId(); // this will not work
 ?>

BUT this is protected method as per documentation so will not be available to call outside class

like image 25
Chetan Sharma Avatar answered Dec 06 '22 09:12

Chetan Sharma