yii2: The default scenario of Model can't be overridden.
What steps will reproduce the problem?
class MyForm extends Model
{
const SCENARIO_DEFAULT = self::SCENARIO_CREATE;
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
}
$form = new MyForm();
echo $form->scenario;
What is the expected result?
create
What do you get instead?
default
Additional info
I can’t write:
public function fields()
{
// PHP Notice – yii\base\ErrorException Undefined index: default
return $fields = $this->scenarios()[$this->scenario];
}
That why:
// \yii\base\Model
private $_scenario = self::SCENARIO_DEFAULT;
To fix it I can rewrite init() method - IMHO: not elegantly.
| Q | A |
|---|---|
| Yii version | 2.0.9 |
| PHP version | > 7 |
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 15 (10 by maintainers)
If you’re just wanting to use the const
SCENARIO_CREATEwhy not inherit it fromSCENARIO_DEFAULTI want to be able to define my scenarios once, and be able to set the default as needed.
Say, I have a
ModelBthat extendsModelA, the default scenario forModelAisSCENARIO_DRAFT, but the default forModelBshould beSCENARIO_REFURBISHED. Currently this is not possible without redefining several scenario constants inModelB— settingSCENARIO_REFURBISHEDtoSCENARIO_DEFAULT, and then settingSCENARIO_DRAFTto something and crossing my fingers, thatModelAusesstatic::SCENARIO_DRAFTeverywhere. And that nothing uses scenario constants of the parent,ModelA, when interacting with the child,ModelB(which is a very common practice in OOP).And what if
ModelCexends fromModelBand needs to have yet another default scenario?I can create the PR for this.
You could change scenario in
init()or__construct().@Alex-Code I can, but it’s litehack…like all of Yii2