Yii CActiveRecord with Column Named "attributes"

230 views Asked by At

I used the CRUD generator from a legacy database. When searching for a column value I get the following error:

htmlspecialchars() expects parameter 1 to be string, array given (/usr/local/share/yii/framework/web/helpers/CHtml.php:103)

The problem is that the model has an existing column named "attributes" which is creating a conflict. I removed the entry from the _search.php and commented out all instances in the model hoping to at least get it working but no luck. Any suggestions would be appreciated.

Thanks.

1

There are 1 answers

0
Tommy Bravo On BEST ANSWER

Every CActiveRecord instance (or CModel instance for that matter) has a getter/setter named attributes with which all the attributes can be set. This leads to a conflict because the generated crud code uses the attributes attribute expecting it works as described before.

The controller does something like:

$model->attributes=$_POST['ModelClassName'];
// or 
$model->attributes=$_GET['ModelClassName'];

This is meant to set al the (safe) attributes of the model at once. Instead this overwrites the database attribute attributes of your legacy DB model.

This in turn leads to the error you describe, because $_GET['ModelClassName'] and $_POST['ModelClassName'] typically contain arrays of data.

I guess the easiest fix would be to directly call the setter function for the "normal" attributes behavior which would lead to replacing the lines mentioned above with something like the following:

// in the controller
$model->setAttributes($_POST['ModelClassName']);
// and 
$model->setAttributes($_GET['ModelClassName']);

I think rest of the generated CRUD code (the views) could and should be left untouched to make it work.

If you want to know how and why this works, it's best to do some research into the __get and __set magic functions and how they're used in the yii framework.