>[danger] 本篇內容非常重要,務必加深理解!
[TOC]
### 后端代碼
~~~
public $enableCsrfValidation = false;
public function actionCreate()
{
if (Yii::$app->request->isPost) {
$name = $_POST['name'];
$city = $_POST['city'];
$province = $_POST['province'];
# 寫INSERT語句或使用下面的對象操作方法
$model = new Restaurant();
$model->name = $name;
$model->city = $city;
$model->province = $province;
$model->save();
return $this->redirect('index');
}
return $this->render('create');
}
~~~
### 后端驗證
>[info] 驗證要求:三個字段均不為空,且餐館名稱不能大于5個漢字。
**更改數據庫字段類型**
~~~
$this->alterColumn('restaurant', 'name', $this->string(5)->notNull());
$this->alterColumn('restaurant', 'city', $this->string()->notNull());
$this->alterColumn('restaurant', 'province', $this->string()->notNull());
~~~
**重新生成Model**
~~~
yii gii/model --tableName=restaurant --modelClass=Restaurant --ns=common\models
~~~
**實現后端驗證**
~~~
public function actionCreate()
{
$model = new Restaurant();
if (Yii::$app->request->isPost) {
$name = $_POST['name'];
$city = $_POST['city'];
$province = $_POST['province'];
$model->name = $name;
$model->city = $city;
$model->province = $province;
if ($model->save()) {
return $this->redirect('index');
}
}
return $this->render('create', ['model' => $model]);
}
/* @var $model common\models\Restaurant */
<pre><?= json_encode($model->errors) ?></pre>
~~~
### 后端代碼(第二版)
**修改前端提交參數名**
~~~
<input type="text" class="form-control" id="name" name="Restaurant[name]">
<input type="text" class="form-control" id="city" name="Restaurant[city]">
<input type="text" class="form-control" id="province" name="Restaurant[province]">
~~~
**重寫后端代碼**
~~~
public function actionCreate()
{
$model = new Restaurant();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
return $this->redirect(['index']);
}
}
return $this->render('create', ['model' => $model]);
}
~~~
### 探索
- load()函數何時返回true,何時返回false?返回true或false的時候,都做了什么工作?
- save()函數何時返回true,何時返回false?返回true或false的時候,都做了什么工作?
- 使用這樣的模型綁定函數,有什么好處?