Custom field type

Hey, everybody!

I have a lot of switches in my forms, and it’s not practical to do this in each field:


<?= $form->field($model, 'st_active', ['template'=>'{label}{input}'])->checkbox(['class'=>'input-switch-alt'], false) ?>

I’d like to do something like:


<?= $form->field($model, 'st_active')->switch() ?>

And use that template and class as default.

How do I create a custom field in Yii2?


<?php

/*

This how I would do it

1. create a directory in your app called widgets

2. under that new directory create a file name ActiveForm.php with following content

*/


namespace app\widgets;


class ActiveForm extends \yii\bootstrap\ActiveForm {


	public function myCheckbox($model, $attribute)

	{

		return $this->field($model, $attribute, ['template'=>'{label}{input}'])->checkbox(['class'=>'input-switch-alt'], false);

	}

	

}


// then you can use it like so

// in your form change the "use yii\bootstrap\ActiveForm" to  "use app\widgets\ActiveForm"

// display the checkbox

$form->myCheckbox($model, 'my_attribute')

Thank you so much!