1. Print the current model
Plaintext
api\modules\v1\models\PlanTask Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[id] => 3
[group_id] => 015ce30b116ce86058fa6ab4fea4ac63
[config_column_id] => 1
[plan_id] => 1
[sort_order] => 1
[title] => 无线成都1
[config_task_id] => 1
[create_user_id] => 8
[create_name] => 13281105967
[exec_user_id] => 185
[exec_name] => test1
[place] => 地点
[task_info] =>
选题摘要
[task_data] => a:0:{}
[ended_at] => 1530695128
[current_step_id] => 18
[prev_status] => 2
[status] => 1
[created_at] => 1528103128
[updated_at] => 1528188754
)
]
)
2. Now there is a request parameter, tool, which is required. It is a tool identifier: jove: Jove micro-editing; nova: Nova fine-editing, and the validation range is ([jove, nova]).
3. Since tool does not exist in the model api\modules\v1\models\PlanTask, ad-hoc validation is required. The code is as follows:
PHP
use yii\base\DynamicModel;
class VideoEditAction extends Action
{
const TOOL_JOVE = 'jove'; //工具:Jove微编
const TOOL_NOVA = 'nova'; //工具:Nova精编
// 临时验证
$request = Yii::$app->request;
$tool = $request->get('tool');
$dynamicModel = new DynamicModel(compact('tool'));
$dynamicModel->addRule('tool', 'required')
->addRule('tool', 'in', ['range' => [self::TOOL_JOVE, self::TOOL_NOVA]])
->validate();
if ($dynamicModel->hasErrors()) {
$response = Yii::$app->getResponse();
$response->setStatusCode(422, 'Data Validation Failed.');
foreach ($dynamicModel->getFirstErrors() as $message) {
$firstErrors = $message;
break;
}
return ['code' => 20004, 'message' => Yii::t('error', Yii::t('error', Yii::t('error', '20004'), ['firstErrors' => $firstErrors]))];
}
}
4. Testing in Postman, when the tool parameter is not provided, it behaves as expected, as shown in Figure 1.

JSON
{
"code": 20004,
"message": "数据验证失败:Tool不能为空。"
}
5. Testing in Postman, when the tool parameter does not equal ([jove, nova]), it behaves as expected, as shown in Figure 2.
![Testing in Postman, when the tool parameter does not equal ([jove, nova]), it behaves as expected](https://media.shuijingwanwq.com/2018/06/2-2.png)
JSON
{
"code": 20004,
"message": "数据验证失败:Tool是无效的。"
}
