Removing default values from CakePHP result
Posted by ragrawal on March 10, 2008
In most of my MySQL tables, I generally use some default values so as to make sure that the webpage doesn’t show up empty. However, as I was building a utility that allowed users to download their data, I wanted to remove these default values. So I wrote a small function, removeDefaults, that can remove all the default values from CakePHP query result. Its generic and has not hard coding. It uses create() function to get default values and use that to compare results. Below is the function and a demo on how you can call it.
// Insert this code in your in app_model.php
/**
* function: removeDefaults
* @description: Removes fields that contain default values in CakePHP result
* @param $array $results - Result array returned by CakePHP
* @param $array $ignore - Fields that must be ignored
* return - $array
*/
function removeDefaults($results, $ignore = array())
{
$defaults = $this->create(); //load default values
foreach($results as $key => $models){
foreach($models[$this->name] as $field => $value){
if(in_array($field, $ignore)) continue; //
if($value == $defaults[$this->name][$field])
unset($results[$key][$this->name][$field]);
}
}
return $results;
}
You can call the above function from any function available within your model. Here I will show I used it in afterFind
class sample extends AppModel{
function afterFind($results){
$ignore = array(”doctype”); // ignore the ”doctype” field. I want to have its default value
return $this->removeDefaults($result, $ignore);
}
}