Reputation: 1131
I'm using Zend Framework 1.7 with a MySQL 5.0 database for a project I'm doing. Part of the system is a longish form that asks a user for various dates (in dd/mm/yyyy format) as well as some integer fields.
In my MySQL table, all these fields have a default of null. When I come to save the form data with a function in my model (which extends Zend_Db_Table), any blank integers fields are set to 0, and any blank date fields are set to 0000-00-00 - in both cases, they should be null.
I believe this is because Zend_Db_Table->insert() is quoting all values, including blank ones. Is there any way I can alter this behaviour? I'm currently having to loop through groups of fields, setting them to null as appropriate.
Cheers,
Matt
Upvotes: 1
Views: 1304
Reputation: 1131
vartec - thanks for your help. Your ideas gave me a good starting point. I've developed it further, extending Zend_Db_Table, adding a function that will suck the column metadata out of MySQL, and use this to set default values. I've posted a rough draft of it below. I haven't made any attempt to simplify it yet, and have only covered the field types I need immediately. Hopefully, it might help others having the same problem.
public function reformatData($array) {
if (!is_array($array)) {
return false;
}
$cols = $this->info(Zend_Db_Table_Abstract::METADATA);
if (is_array($cols)) {
foreach ($cols as $col) {
if (array_key_exists($col['COLUMN_NAME'], $array)) {
switch ($col['DATA_TYPE']) {
case 'int': case 'tinyint':
if ($array[$col['COLUMN_NAME']] == '') {
$newArray[$col['COLUMN_NAME']] = new Zend_Db_Expr('null');
}
else {
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
}
break;
case 'date':
if ($array[$col['COLUMN_NAME']] == '') {
$newArray[$col['COLUMN_NAME']] = new Zend_Db_Expr('null');
}
elseif(!Zend_Date::isDate($array[$col['COLUMN_NAME']], 'YYYY-MM-dd')) {
$date = new Zend_Date($array[$col['COLUMN_NAME']], null, 'en_GB');
$newArray[$col['COLUMN_NAME']] = $date->toString('YYYY-MM-dd');
}
else {
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
}
break;
case 'datetime':
if ($array[$col['COLUMN_NAME']] == '') {
$newArray[$col['COLUMN_NAME']] = new Zend_Db_Expr('null');
}
elseif(!Zend_Date::isDate($array[$col['COLUMN_NAME']], 'YYYY-MM-dd HH:MM')) {
$date = new Zend_Date($array[$col['COLUMN_NAME']], null, 'en_GB');
$newArray[$col['COLUMN_NAME']] = $date->toString('YYYY-MM-dd HH:MM');
}
else {
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
}
break;
default:
$newArray[$col['COLUMN_NAME']] = $array[$col['COLUMN_NAME']];
break;
}
}
}
return $newArray;
}
else {
return false;
}
}
Upvotes: 1