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
Requires
- php: >=5.4.0
README
The use case
You need form input for separate model objects in your application.
Installation
$ composer require flaviovs/yii2-form
How to
-
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; }
-
Add the
modelAttributes()
function, which indicates which form attributes contain models to be loaded on submission:protected function modelAttributes() { return ['post', 'comment']; }
-
Add validation rules for the models:
protected function rules() { return [ [$this->modelAttributes(), 'safe']; ]; }
-
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();
-
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(); }