I am using Yii2 and I want to create custom active form field type.
For example creatig a text input form field is happending like this:
$form = ActiveForm::begin();
$form->field($model, 'attribute_name')->textInput(['maxlength' => true])
I want to make custom json input field type with special rendering and all and use it like this:
$form->field($model, 'attribute_name')->JsonInput(['maxlength' => true]);
and not like this:
$form->field($model, 'attribute_name')->widget('trntv\aceeditor\Widget','mode'=>'json);
How can I extend the yii\widgets\ActiveForm
so that I can add my custom form field types? Is it possible at all?
The only relatable info about this I found is in the Yii forum, but there the usage format is different:
$form->myCheckbox($model, 'attribute_name');
and I want the usage to be like the yii form types:
$form->field($model, 'attribute_name')->JsonInput(['maxlength' => true]);
You need to create:
ActiveField
class with method JsonInput()
(which calls widget()
with your widget configuration).ActiveForm
class with changed fieldClass
property to your custom ActiveField
class. You may add @method \my\custom\ActiveField field(\yii\base\Model $model, string $attribute, array $options = [])
to PHPDoc of your ActiveForm
to get better code completion.You may also skip creating own ActiveForm
and change fieldClass
ad hoc:
$form = ActiveForm::begin([
'fieldClass' => \my\custom\ActiveField::class,
])
but you will need to repeat it every time and you will not get code completion for your custom methods in ActiveField
.