flaviovs / yii2-form
为 Yii2 的复合模型(即表单)
0.0.5
2019-05-11 01:18 UTC
Requires
- php: >=5.4.0
README
使用场景
你需要在应用中为单独的模型对象提供表单输入。
安装
$ composer require flaviovs/yii2-form
如何使用
-
创建你的表单模型。将组成模型作为正常属性添加
class MyForm extends fv\yii\form\Model { /** @var \app\models\Post */ public $post; /** @var \app\models\Comment */ public $comment; }
-
添加
modelAttributes()
函数,该函数指示哪些表单属性包含在提交时要加载的模型protected function modelAttributes() { return ['post', 'comment']; }
-
为模型添加验证规则
protected function rules() { return [ [$this->modelAttributes(), 'safe']; ]; }
-
像平常一样在你的视图中添加输入控件。只需记住要引用表单的模型属性,而不是表单模型本身。
/** @var \fv\yii\form\Model $model */ $form = ActiveForm::begin(); echo $form->field($model->post, 'title'); echo $form->field($model->comment, 'body'); ActiveForm::End();
-
像平常一样处理表单
$model = new MyForm([ 'post' => new Post(), 'comment' => new Comment(), ]); if ($model->load(\Yii::$app->request->post()) && $model->validate()) { $model->post->save(); $model->comment->save(); }