Changes
Title
unchanged
Optimize Scenarios for yii2
Category
unchanged
Tutorials
Yii version
changed
2.0
Tags
changed
model, model validation, model,validation rules
Content
changed
[...]
One way to avoid this disorder is to encapsulate the information defined for the scenarios and to have a single point of customization.
For this we need to create constants for each scenario, note: once you define a scenario, you will need to use scenarios for any database edition that uses this model.
**In model**
```php
class MyModel extends \yii\db\ActiveRecord
{
const SCENARIOCR
IEATE = 'scenariocr
ieate';
const SCENARIOUPDATE = 'scenarioupdate';[...]
return [
self::SCENARIOCRIEATE => ['user_id', 'name', 'desc', 'published','date_create'],
self::SCENARIOUPDATE => ['user_id', 'name', 'desc', 'date_update'],
];[...]
$allscenarios = $this->getCustomScenarios();
// published not required
$allscenarios[self::SCENARIOCRIEATE] = array_diff($allscenarios[self::SCENARIOCR
IEATE], ['published']);
return $allscenarios;[...]
$allscenarios = $this->ModifyRequired();
return [
[$allscenarios[self::SCENARIOCRIEATE], 'required', 'on' => self::SCENARIOCR
IEATE],
[$allscenarios[self::SCENARIOUPDATE], 'required', 'on' => self::SCENARIOUPDATE],
[['user_id'], 'integer'],[...]
```
O gGetCustomScenarios
será usado para quando for necessário fazer modificações de colunawill be used for when you need to make column modifications.
OThe ModifyRequired
é utilizado para remover do required, pois neste momento será utilizadois used to remove from the required, because at this point will be used getCustomScenarios
para ofor the save.
**In Controller**
```php
public function actionIndex()
{
$model = new MyModel;
$model->scenario = 'scenariocr
ieate';
if ($model->load(\Yii::$app->request->post())){
// get all scenarios
$allscenarios=$model->getCustomScenarios();
// force my columns
if($model->save(
true, $allscenarios[$this->scenario])){
//return true
}
}
}
```[...]