Removing default values from CakePHP result

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])
      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);


Posted in PHP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s