How to add id preix for field in activeForm?
Asked Answered
C

3

6

i have two forms holds the same model attributes, since Yii2 generate the field id to be ModelName-fieldName so the field generated will be as follow:

<select name="Channel[channel]" class="form-control" id="channel-description">

i have tried to use fieldConfig in Activeform but it doesn't add the id to the field itself.

Carbrey answered 2/5, 2016 at 7:56 Comment(0)
H
6

You should simply use the third parameter of ActiveForm::field() :

$options : The additional configurations for the field object.

e.g. :

$form->field($model, 'channel', ['inputOptions' => ['id' => 'channel-description']])

Read more about ActiveForm::field().

But if you really want to add a prefix to all your fields ids, you should override ActiveForm.

Heshvan answered 2/5, 2016 at 8:6 Comment(4)
this will generate the id over the field container to be like: <div class="col-lg-8 field-channel-description required has-error" id="mynewId">Carbrey
what i am looking for is to add prefix for every field id not field container, do you think i need to override the activeFormCarbrey
i can use the second parameter for dropDownList and add dropDownList(\yii\helpers\ArrayHelper::map($channels, 'id', 'desc'),['prompt'=>'--channels--','id'=>'myOwnId'] but in this case i will loose the Yii ValidationCarbrey
Answer updated. And just tried the validation with custom id, it works.Heshvan
B
1

If you want save input id structure "{model}-{attribute}".

Use yii\helpers\Html::getInputId() for generate "{model}-{attribute}" input id and complete it with your custom prefix.

$form->field($model, 'name')->textInput(['id' => 'custom-' . Html::getInputId($model, 'name')])
Bermuda answered 2/6, 2018 at 11:50 Comment(0)
D
0

If you set a custom id for the input element, you may need to adjust the [[$selectors]] accordingly.

<?= $form->field($searchModel, 'regId',[
            'selectors' => ['input' => '#company-vacancy-regId'],
            'inputOptions' => ['id' => 'company-vacancy-regId'],
        ])->widget()?>
Doubleminded answered 27/3, 2020 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.