I’m using PostgreSQL, don’t know if it’s same for MySQL
In a table I have a field numeric(12,2) - it’s optional so it can be NULL
in the model rules I set the CNUmberValidator so that it checks if entered value is a number
The problem is if a user does not enter anything (because it’s optional) the CNumberValidator just return because it’s allowed to be empty
and then I’m getting this error:
[i]CDbCommand failed to execute the SQL statement: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type numeric: ""INSERT INTO "table" …
I had a similar problem, I actually wanted NULL values to be inserted in my database whenever any field was left blank. Also I wanted all input to be trimmed. So I extended ActiveRecord like that:
class MyCActiveRecord extends CActiveRecord {
protected function beforeValidate($scenario) {
$attributes = $this->getSafeAttributeNames($scenario);
foreach($attributes as $attr) {
if (gettype($this->$attr) == "string") {
$this->$attr = trim(str_replace("\r","",$this->$attr));
}
}
return parent::beforeValidate($scenario);
}
public function beforeSave() {
$attributes = $this->getSafeAttributeNames($this->scenario);
foreach($attributes as $attr) {
if ($this->$attr === "") {
$this->$attr = null;
}
}
return parent::beforeSave();
}
}