Hello everyone.
As we know it’s very useful (for security reasons) to convert special characters to html entities when we want to store data in a database.
For this purpose in Yii we have CHtml::encode() function for a single string and CHtml::encodeArray() for an array of strings.
So in my controller I have this code
$model = new Books;
$model->attributes=CHtml::encodeArray($_POST['Books']);
$model->save()
This works great. But now if I want to load the data from my database into my form for editing the strings remain encoded, that is my single quote for example is shown as
& #039;
in my textField. This is not good.
Unfortunately we don’t have corresponding CHtml::decodeArray() function. So I desided to slightly change CHtml::encodeArray() and got this
private function decodeArray($data)
{
$d=array();
foreach($data as $key=>$value)
{
if(is_string($key))
$key=htmlspecialchars_decode($key,ENT_QUOTES);
if(is_string($value))
$value=htmlspecialchars_decode($value,ENT_QUOTES);
else if(is_array($value))
$value=self::decodeArray($value);
$d[$key]=$value;
}
return $d;
}
Now to load my data to my form for editing I desinged a little trick. Here it is
public function actionKedit()
{
...
$model = Books::model()->findByPk($_GET['id']);
$model_dec = new Books;
$model_dec->attributes=$this->decodeArray($model);
$this->render('kedit',array('model'=>$model_dec));
...
}
It works, but I’d like to know if it’s a right solution or is there a better, more effective way to assign to $model->attributes the array of decoded strings?
Thanks.