添加餐馆(二)
最后更新于:2022-04-01 11:17:37
>[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的时候,都做了什么工作?
- 使用这样的模型绑定函数,有什么好处?