Save a field to default value of your table

A small issue you can have when you use CakePHP is when you want to save your current model using $this->request->data and one of your field can be left to the default value of your table. Enough blabla, let’s see an example to understand the problem.

Table posts (taken from http://book.cakephp.org/2.0/en/getting-started.html#creating-the-blog-database)

CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    subtitle VARCHAR(50) DEFAULT 'no subtitle',
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);

I only added the field subtitle for this example which is set to ‘no subtitle’ by default, I know this example is useless, you could put NULL instead or whatever you want.

Here’s a part of the Post model validation.

public $validate = array
(
	'subtitle' => array
	(
		'rule' => 'notEmpty',
		'required' => false,
		'allowEmpty' => true
	)
);

Basic validation, we put the notEmpty rule, then not required and allowEmpty to true. It can be tricky to see notEmpty and allowEmpty, but the first is the rule saying we accept whatever we type in. The other says we can left it empty. And required means that the array key subtitle does not have to be present in $this->request->data to validate, which is a part of what we need.

More about it http://book.cakephp.org/2.0/en/models/data-validation.html

So if you create a new post using a form and leave the subtitle field blank, CakePHP will set $this->request->data[‘Post’][‘subtitle’] equals to “”. It becomes an issue, because, it will save in your database the subtitle but with an empty character. The best is to let the database do the job of setting by default its value.

I had a little “idea” you can use in your controller :

if(empty($this->request->data['Post']['subtitle']))
{
    unset($this->request->data['Post']['subtitle']);
}
/* ... then you save your data */

This would unset from $this->request->data the subtitle key, so Cakephp will not try to save this field, and the database will deal with the default value and in our example set it to ‘no subtitle’.

You can probably write it in the beforeSave function to make it more proper and make it work for the edit action too.

I believe it’s not the best way to make it, leave a comment if you have some better ideas 😉