0

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]);
Chris
  • 3
  • 3

1 Answers1

0

You need to create:

  1. Custom ActiveField class with method JsonInput() (which calls widget() with your widget configuration).
  2. Custom 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.

rob006
  • 21,383
  • 5
  • 53
  • 74
  • Thank you for the help! It worked like a charm. The only thing is that the new custom field types are not autocomoleted or recognized from where they come. I included `@method \my\custom\ActiveField field(\yii\base\Model $model, string $attribute, array $options = [])` in my custom `ActiveForm` class. – Chris Apr 03 '18 at 15:22