Question

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.

Était-ce utile?

La 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.

Autres conseils

I recommend creating getter/setter for fields where it can occur and filter it there.

Something like this in case of field comment:

// Make field $comment private so get/set will work
private $comment = '';
public function getComment()
{
    return clear_function($this->comment);
}

public function setComment($value)
{
    // Could clear here too if you want, so it will be stored clean in db
    $this->comment = $value;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top