flaviovs/yii2-form

Composite models (a.k.a forms) for Yii2

Installs: 960

Dependents: 0

Suggesters: 0

Security: 0

Stars: 1

Watchers: 2

Forks: 0

Open Issues: 0

Type:yii2-extension

0.0.5 2019-05-11 01:18 UTC

This package is auto-updated.

Last update: 2024-11-11 14:58:53 UTC


README

The use case

You need form input for separate model objects in your application.

Installation

$ composer require flaviovs/yii2-form

How to

  1. Create your form model. Add composing models as normal attributes:

    class MyForm extends fv\yii\form\Model
    {
    	/** @var \app\models\Post */
    	public $post;
    
    	/** @var \app\models\Comment */
    	public $comment;
    }
  2. Add the modelAttributes() function, which indicates which form attributes contain models to be loaded on submission:

    protected function modelAttributes()
    {
    	return ['post', 'comment'];
    }
  3. Add validation rules for the models:

    protected function rules()
    {
        return [
            [$this->modelAttributes(), 'safe'];
        ];
    }
  4. Add input controls to your views as you normally would. Just remember to reference model attributes of the form, instead of the form model itself.

    /** @var \fv\yii\form\Model $model */
    
    $form = ActiveForm::begin();
    
    echo $form->field($model->post, 'title');
    echo $form->field($model->comment, 'body');
    
    ActiveForm::End();
  5. Process the form as you normally do:

    $model = new MyForm([
    	'post' => new Post(),
    	'comment' => new Comment(),
    ]);
    if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
    	$model->post->save();
    	$model->comment->save();
    }

Support

https://github.com/flaviovs/yii2-form