Null Behavior
Problems with default NULL fields not being very NULL'ish ?
This is just a small script to make sure some values arent saved if they are supposed to be NULL in the database.
*** Updated ***
Added check on length of string, to avoid the 0 being caught as a nullable value.
*** Updated ***
Added check on length of string, to avoid the 0 being caught as a nullable value.
Use
Model Class:
Download code
<?php
var $actsAs = array('Null' => array('file_id','parent_id'));
?>
Code
Model Class:
Download code
<?php
class NullBehavior extends ModelBehavior {
var $settings = array();
/**
* Enter description here...
*
* @param AppModel $model
* @param unknown_type $config
*/
function setup(&$model, $config = array() )
{
$this->settings[ $model->name ] = $config;
}
/**
* Enter description here...
*
* @param AppModel $model
*/
function beforeSave(&$model)
{
$config = $this->settings[$model->name];
foreach ( $config AS $field )
{
if(
true === array_key_exists($field,$model->data[$model->name] ) &&
true === empty( $model->data[$model->name][$field] ) &&
0 === strlen( $model->data[$model->name][$field] ) )
{
unset($model->data[$model->name][$field]);
}
}
return true;
}
}
?>
Comments
Comment
1 Might fail to save a field with a 0 value
I did something similar, but the test :
true === empty( $model->data[$model->name][$field] )
will be true if the value is set to 0 (string or numeric), therefore it might be impossible to save a field whose value is 0.
Adding the following in the test expression fixes this :
&& $model->data[$model->name][$field] != "0"
Comment
2 save NULL fields
//unset($model->data[$model->name][$field]);
$model->data[$model->name][$field] = NULL;
Comment
3 A slightly different version
function beforeSave() {
/**
* Checks table metadata for fields which allows NULL and set the value
* to NULL when they are empty
*
* TODO: probably make this a behavior?
*/
$tableInfo = $this->_tableInfo->get();
foreach ($tableInfo as $field) {
if ($field['null']) {
if (isset($this->data[$this->name][$field['name']]) && $this->data[$this->name][$field['name']] === '') {
$this->data[$this->name][$field['name']] = null;
}
}
}
return true;
}
Comment
4 That looks good
Hey Derick, your code looks much more better.
Comment
5 Updating Dericks Code
function beforeSave() {
/**
* Checks table metadata for fields which allows NULL and set the value
* to NULL when they are empty
*
* TODO: probably make this a behavior?
*/
$tableInfo = $this->schema();
foreach ($tableInfo as $name => $field) {
if ($field['null']) {
if (isset($this->data[$this->name][$name]) && $this->data[$this->name][$name] === '') {
$this->data[$this->name][$name] = null;
}
}
}
return true;
}