我有 MyEntity.php 模型。作为模型脚本的一部分,定义了一些规则和一些场景:
public function rules()
{
return [
[['myentity_id', 'myentity_title', 'myentity_content', 'myentity_date'], 'required'],
[['myentity_id'], 'integer'],
[['myentity_title', 'myentity_content'], 'string', 'max' => 120],
[['myentity_date'], 'safe'],
];
}
public function scenarios()
{
$scenarios = parent::scenarios();
$scenarios['scenario_one'] = ['myentity_id', 'myentity_title'];
$scenarios['scenario_two'] = ['myentity_id', 'myentity_content'];
return $scenarios;
}
我需要能够有不同的场景,并且对于不同的操作,只有某些验证(通过参数)才能处于事件状态。例如,scenario_one 用于 actionOne,scenario_two 用于 actionTwo 等。
这是 Controller 的一小部分代码:
public function actionOne($id)
{
$modelMyEntity = $this->findModel($id);
$modelMyEntity->scenario = 'scenario_one';
.
.
.
}
public function actionTwo($id)
{
$modelMyEntity = $this->findModel($id);
$modelMyEntity->scenario = 'scenario_two';
.
.
.
}
现在我想要一个根本不应该有任何验证的场景三。我将在代码中进行额外的检查,以防止在数据库中存储时失败。我只需要确保没有应用任何验证,因为它会阻止我的表单提交。如果我不应用任何方案,则应用默认方案(所有列出的验证都将处于事件状态,这与我需要的方案完全相反)。
最佳答案
为了能够做到这一点,你需要做一些事情(包括你几乎自己做的事情):
在您的 Controller 中,编写
$modelMyEntity->scenario = 'scenario_three';
在模型中,在
scenarios()
方法中添加一个额外的场景数组'scenario_three':
像这样:
$scenarios['scenario_three'] = ['myentity_id', 'myentity_content'];
- 最后,大部分更改都需要在
rules()
中进行,因为您需要添加包含或排除特定场景的位置。
基本上,您现在可以在每个规则中编写 except
条件并指出哪些属性不符合哪种情况。因此,在您的示例中,假设我们排除 scenario_three
的所有属性:
[['myentity_id', 'myentity_title', 'myentity_content', 'myentity_date'], 'required', 'except' => 'scenario_three'],
[['myentity_id'], 'integer', 'except' => 'scenario_three'],
[['myentity_title', 'myentity_content'], 'string', 'max' => 120, 'except' => 'scenario_three'],
[['myentity_date'], 'safe'],
这与忽略规则的方法略有不同,但我觉得这更有吸引力,因为将来为这种情况添加/删除特定属性会更容易,其他开发人员也会更容易(如果有超过只有你)来了解你想要做什么。
但我认为@iStranger 的解决方案也有效(简单得多)。
关于validation - 如何在没有验证规则的情况下在 Yii2 中创建场景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39689920/