Yii2. Form get Input Id

时间:2016-07-11 21:34:46

标签: php yii2 active-form

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.

2 个答案:

答案 0 :(得分:15)

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'); ?>

答案 1 :(得分:2)

默认情况下,he字段的id为$model-$attribute,即

如果您使用User模型和username以表格形式提交,即

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

ID为user-username

您也可以手动为字段指定id。

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

在这种情况下,输入的ID将为my_id

根据最新评论进行编辑:(我没有尝试过,但根据文档解释)

textInput函数返回$ this http://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#textInput()-detail

因此getInputIdhttp://www.yiiframework.com/doc-2.0/yii-widgets-activefield.html#getInputId()-detail)必须可以调用

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

但这是受保护的方法根据文档,因此无法在课外调用