Hello,
I’ve came across a clash of variable names between my application and Yii framework.
Here is what happened:
-
I have 2 models: ‘DataVersion’ & ‘Attribute’
-
One ‘DataVersion’ has many ‘Attribute’
Then I created a form for creating data versions, added validation rules and finally a controller for validating and saving new records. The basic stuff everyone knows about!
public function actionCreate() {
$model = new DataVersion;
if ($_POST['DataVersion']) {
$model->attributes = $_POST['DataVersion'];
if ($model->save()) {
$this->redirect(array('view', 'id' => $model->data_version_name));
}
}
$this->render('create', array(
'model' => $model,
));
}
And this didn’t work. I was staring at my monitor to only see error messages telling me my fields couldn’t be blank. My post was not validated. I checked my validation rules almost certain that there was an error somewhere, after all I’ve done this many times and this is a really well known process. Lots of debugging, pulled my hair, almost broke my desk with my head (or the other way round, I don’t quite remember)… I finally discovered that ‘setAttributes’ was working.
$model->setAttributes($_POST['DataVersion']);
But I still couldn’t figure out why… but came the light. Everything because of what is quoted below, in DataVersion model:
public function relations() {
return array(
'attributes' => array(self::HAS_MANY, 'Attribute', 'data_version'),
);
}
attributes! $model->attributes was an existing variable and therefore the Yii setter (in CComponent) couldn’t do its magic and invoke “setAttributes”.
Failed
Can anyone think about other variable names which shouldn’t be used?