phpactiverecordyiismart-quotes

Yii - remove smart quotes for all active records


I have an application that allows a user to import/enter information, which gets saved to the MySQL database using a Yii active record, and I have a few users who copy/paste text that has Microsoft smart quotes. This is an issue when the data is parsed on the iPhone implementation of the site, so I need a way to get rid of all the smart quotes everywhere.

I found a php function that will remove these characters from a piece of text, but I was wondering if there is a way in Yii to have the function get called every time text is saved to the database.


Solution

  • You can extend CActiveRecord overriding beforeSave method in the following manner:

    class ActiveRecord extends CActiveRecord
    {
        protected function removeMagicQuotes($value)
        {
            return your_function_remove_magic_quotes($value);
        }
    
        protected function beforeSave()
        {
            $attributes = array_keys($this->getAttributes());
            foreach ($attributes as $attribute)
                $this->$attribute = $this->removeMagicQuotes($this->$attribute);  
            return parent::beforeSave();
        }
    }
    

    This one will remove magic quotes for all attributes declared in active record. As an alternative you can override beforeValidate method instead of beforeSave to remove quotes just before validation.