Refactoring Cactiveform

So when we are using CActiveForm we need to supply $model to every field() call. Here is what i was wondering:

a- Add a public property to CActiveForm called model

b- Refactor field() to accept it as last and optional parameter. The very first line inside the method would be something like:


 

$model = (isset($model))? $model: $this->model;



What do we have now:




<?php $form = yii\widgets\ActiveForm::begin(); ?>

    <?php echo $form->field($model, 'username')->textInput(); ?>

    <?php echo $form->field($model, 'password')->passwordInput(); ?>

    <div class="form-actions">

        <?php echo Html::submitButton('Login'); ?>

    </div>

<?php yii\widgets\ActiveForm::end(); ?>



What i am hoping to achieve:




<?php $form = yii\widgets\ActiveForm::begin('model' => $model); ?>

    <?php echo $form->field('username')->textInput(); ?>

    <?php echo $form->field('password')->passwordInput(); ?>

    <div class="form-actions">

        <?php echo Html::submitButton('Login'); ?>

    </div>

<?php yii\widgets\ActiveForm::end(); ?>



Why i was wondering along these lines?

Most of my forms, if not all, relate to only one model and its just bit painful to type $mod[TAB] over and over.

With this approach we could save some typing if its a single-model form while still letting user override $model inside field() calls for multi-model forms.

If this gets approved i could take the task of doing a fork, updating codebase and submitting a pull request.

Looks reasonable and logical to me.

IMO: if we’ll decide to implement this proposal better to keep field() method untouched. I propose to introduce new method which would look something like as follows:




<?php


class ActiveForm extends Widget

{

	// ...


	/**

	 * @var Model

	 */

	public $model;


	/**

	 * @param string $attribute

	 * @param array $options

	 * @return ActiveField

	 */

	public function item($attribute, $options = array())

	{

		return $this->field($this->model, $attribute, $options);

	}

}



You might consider adding your proposal to ActiveForm improvements.

It’s based on the same idea. Forms related to only one model seem to be very common and repeatedly typing $model over and over again could be avoided.

However, the use case of several models that need to be accessed in a mixed up order still needs to be supported without too much hassle.