Difference between revisions of "How do I store empty values as NULL in the database?"
From Joomla! Documentation
(Created page with "If you want to store empty values as NULLs into the database, you need to override JTable::store() and JModelAdmin::prepareTable(). Add following snippets of code into your co...") |
(commenting code a bit) |
||
(4 intermediate revisions by one other user not shown) | |||
Line 4: | Line 4: | ||
<source lang="php"> | <source lang="php"> | ||
public function store($updateNulls = true) { | public function store($updateNulls = true) { | ||
+ | /* overload JTable::store() to enable updating values into NULL */ | ||
return parent::store(true); | return parent::store(true); | ||
} | } | ||
Line 12: | Line 13: | ||
protected function prepareTable($table) | protected function prepareTable($table) | ||
{ | { | ||
+ | /* define which columns can have NULL values */ | ||
$defnull = array('array','of','columns','that','can','have','null','value'); | $defnull = array('array','of','columns','that','can','have','null','value'); | ||
foreach ($defnull as $val) | foreach ($defnull as $val) | ||
+ | /* define the rules when the value is set NULL */ | ||
if (!strlen($table->$val)) | if (!strlen($table->$val)) | ||
$table->$val = NULL; | $table->$val = NULL; | ||
} | } | ||
</source> | </source> | ||
− | [[Category:Tips and | + | [[Category:Development Tips and Tricks]] |
+ | [[Category:Database]] | ||
+ | [[Category:Development FAQ]] |
Latest revision as of 11:23, 16 May 2013
The "J2.5" namespace is a namespace scheduled to be archived. This page contains information for a Joomla! version which is no longer supported. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.
If you want to store empty values as NULLs into the database, you need to override JTable::store() and JModelAdmin::prepareTable(). Add following snippets of code into your component's admin/tables/nameoftable.php and admin/models/nameofeditview.php
admin/tables/nameoftable.php
public function store($updateNulls = true) {
/* overload JTable::store() to enable updating values into NULL */
return parent::store(true);
}
admin/models/nameofeditview.php
protected function prepareTable($table)
{
/* define which columns can have NULL values */
$defnull = array('array','of','columns','that','can','have','null','value');
foreach ($defnull as $val)
/* define the rules when the value is set NULL */
if (!strlen($table->$val))
$table->$val = NULL;
}