Focus on Yii2 forms

Hello!

In Yii1 I used the ‘focus’ property of CActiveForm to set the focus on the first enabled first of the form. If the form model has errors, the focus went to the first error field.

Thats the code:


<?php $form = $this->beginWidget('GxActiveForm', array(

	'id' => 'documento-form',

	'enableAjaxValidation' => true,

        'focus'=>($model->hasErrors()) ? '.error:first' : 'input:visible:enabled:first',   ====> this property

));

?>

I tried this in Yii2 and it works, but only when the form doesn’t have errors. I couldn’t focus the first error field as above.


I $this->registerJs(

    '$("document").ready(function(){ $("input:visible:enabled").first().focus(); });'

); ?>

I know the ‘focus’ property was dropped in Yii2. How can I get the same behavior then?

Thanks!

Hi Almir,

By using this


<?= $form->field($model, 'username', ['inputOptions' => 

    ['autofocus' => 'autofocus', 'class' => 'form-control', 'tabindex' => '1']])

 ?>

You can achieve this…

And/Or, you can achieve it with the following in JS file included in each page(When required)


$("form input:text, form textarea").first().focus();

But what in case of validation errors?

How can I set the focus on the first validation error input box?

Enable client side validations or Use jQuery/javascript validations for highlighting the first error field…

Thanks!