Emanuel A.
Emanuel A.

Reputation: 112

Yii model rules "Failed to set unsafe attribute"

I've looking but can't get It to work.

These are my rules in model Acta.php

public function rules()
{
    return array(
        array('dominio', 'required'),
        array('numero, velocidad, grupo, dni, cuit, plan_pago_id', 'numerical', 'integerOnly'=>true),
        array('foto, observaciones, situacion, infractor, dominio, tipo_vehiculo, marca, modelo, domicilio, codigo_postal, localidad, provincia, tipo_multa, usuario', 'length', 'max'=>255),
        array('hora', 'length', 'max'=>11),

        //Here is the problem with only this three attributes
        array('municipio, cinemometro, fecha_labrada', 'safe', 'on'=> 'create,update'),

        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, numero, fecha_labrada, velocidad, grupo, foto, observaciones, situacion, infractor, dominio, dni, cuit, tipo_vehiculo, marca, modelo, domicilio, codigo_postal, localidad, provincia, tipo_multa, hora, usuario, plan_pago_id', 'safe', 'on'=>'search'),
    );
}

And this is the code on controller ActaController.php

public function actionCreate()
{
    $model = new Acta;

    if(isset($_POST['Acta']))
    {

        ...
        code setting data on $_POST['Acta']
        ...

        $model->attributes = $_POST['Acta'];
        $model->save();
    }

    $this->redirect(array('ingresar'));

}

I can't see the problem. Should be working right?

EDIT:
I thought that the scenario was set automatically. I was wrong.
To fix this the scenario must be set before the attributes:

...
$model->setScenario('create');
$model->attributes = $_POST['Acta'];
...

Upvotes: 4

Views: 9563

Answers (1)

Ali MasudianPour
Ali MasudianPour

Reputation: 14459

Before you save, You absolutely have some errors. To be aware about errors do like below:

if($model->validate()){
    //NO ERRORS, SO WE PERFORM SAVE PROCESS
    $model->save()
}else{
    //TO SEE WHAT ERROR YOU HAVE
    CVarDumper::dump($model->getErrors(),56789,true);
    Yii::app()->end();
    //an alternative way is to show attribute errors in view
}

On the other hand, it seems you set some attributes as safe on specific scenarios. But you did not set the scenario.

to set scenario, do like below:

$model->setScenario('THE SCENARIO NAME');

Or:

$model=new YOURMODELNAME('SCENARIO NAME');

I hope it help

Upvotes: 4

Related Questions