Yii check scenario in beforeSave()

2.7k views Asked by At

For one action I need transform $album_id before save it to DB in model function beforeSave() i do:

// преобразовать album -> album_id
$album_id=array();
foreach($this->string2array($this->album, '\|') as $one)
    $album_id[]=Album::model()->findByAttributes(array('album' => $one))->id;

$this->album_id = $this->array2string($album_id);

but for another action I don't need this transform, because $album_id is already in proper state. So I set scenario 'batchcreate' in that action:

public function actionCreate()
{
    Yii::import('ext.multimodelform.MultiModelForm');

    $model = new Album('create'); 

    $song = new Song();
    $song->setScenario('batchcreate');
    ...
}

and try to check this scenario in model:

if(!($this->scenario === 'batchcreate')) {
    // преобразовать album -> album_id
    $album_id=array();
    foreach($this->string2array($this->album, '\|') as $one)
        $album_id[]=Album::model()->findByAttributes(array('album' => $one))->id;
    $this->album_id = $this->array2string($album_id);
}

but the condition is always true. Why my scenario doesn't set or doesn't check in if statement? Or maybe it's better to check not scenario, but make another variable, so how to set its value for 2 different cases?

my whole beforeSave():

protected function beforeSave()
    {
        if(parent::beforeSave())
        {

            // преобразовать whoes -> who
            $who=array();
            foreach($this->string2array($this->whoes) as $one) {
                $userrow = User::model()->findByAttributes(array('username' => $one));
                if($userrow) $who[]=CHtml::encode($userrow->id);
                else $who[]=$one;                              
            }
            $this->who = $this->array2string($who); 


            //var_dump( $this->scenario );
            if(!($this->scenario == 'batchcreate')) {
            //if($this->notbatchcreate == 'yes') {
                // преобразовать album -> album_id
                $album_id=array();
                foreach($this->string2array($this->album, '\|') as $one)
                    $album_id[]=Album::model()->findByAttributes(array('album' => $one))->id;
                $this->album_id = $this->array2string($album_id);
            }



            return true;
        }
        else
            return false;
    } 
2

There are 2 answers

0
Maug Lee On

Instead of

$song = new Song();
$song->setScenario('batchcreate');

you can simply do

$song = new Song('batchcreate');

In beforeSave()

if ( $this->scenario != 'batchcreate' ) {
    echo "good - scenario is not batchcreate";
    die();
}
echo 'nope...';
var_dump($this->scenario);
die();
0
topher On

Switch the order: call parent::beforeSave() after your code for checking the scenario. The inherited method beforeSave() may be altering your scenario.