freshest
freshest

Reputation: 6241

CakePHP - Set Default Field Values in the Model

How do you set a default value for a field in a model?

EDIT:

I have tried the method using _schema as suggested, but the default value is not being used.

public $_schema = array(
    'newsletter' => array(
        'default' => 1
    ),
);  

Upvotes: 8

Views: 10534

Answers (5)

Álvaro González
Álvaro González

Reputation: 146350

You can set the value in database and get it managed in schema, e.g.:

public $items = array(
    'id' => array('type' => 'integer', 'null' => false, 'default' => null, 'length' => 10, 'unsigned' => false, 'key' => 'primary'),
    'quantity' => array('type' => 'decimal', 'null' => false, 'default' => '1.00', 'length' => '12,2', 'unsigned' => false),
    //                                                        ^^^^^^^^^^^^^^^^^^^
    'indexes' => array(
        'PRIMARY' => array('column' => 'id', 'unique' => 1),
    ),
    'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_spanish_ci', 'engine' => 'InnoDB')
);

This default value can be read later in model or controller though the model's schema property:

// Controller example
$itemSchema = $this->Item->schema();
$defaultQuantity = $itemSchema['quantity']['default'];
// ... or:
$quantityInfo = $this->Item->schema('quantity');
$defaultQuantity = $quantityInfo['default'];

In recent PHP versions it can be a one-liner:

$defaultQuantity = $this->Item->schema('quantity')['default'];

This works in Cake/2.5 with MySQL adapter (no idea of other scenarios).

Upvotes: 1

Linas Butenas
Linas Butenas

Reputation: 171

As the above suggestions do not work for me, so I have found my own. The answer is very similar to the written above, but with one little correction. (works with CakePHP 2.6.1)

The default value can be set in the controller in add function ("request" is needed).

$this->request->data['Country']['hasFlag'] = 1; 

Full code example:

public function add() {
    if ($this->request->is('post')) {
        $this->Country->create();
        if ($this->Country->save($this->request->data)) {
            ...
        } else {
            ...
        }
    }
    $this->request->data['Country']['hasFlag'] = 1;  // default value passing to the view
}

Some philosophy:
1) Why this is needed - If we have a boolean attribute in the database, the newly created object in Cakephp does not take into the account default values from database. And if we leave checkbox unchecked in the Add form of the new object and submit it to the database - it means this attribute value is false (not value not set)
2) Is this an ideal place to set default value? - No, this is not an ideal place, as all information about the Object and its data must be in the Model, but I haven't managed to assign default value in the model. Even using _schema variable or create function.

Upvotes: 1

jakubplus
jakubplus

Reputation: 317

databases get big, so you cannot remember all those defaults you've set. Let's keep it simple:

  1. You set default values in the controller (it's easy to read the code, if default values for certain actions are set at the beginning as class properties).

For example:

class UsersController extends AppController {
private $registerDefaults = array(
    'group_id' => '1'
);

public function register() {
    if ($this->request->is('post')) {
        /*
        * This is where you set default value
        * Here's what I do for default group that user should be assigned to
        */
        $this->request->data['User']['group_id'] = $this->registerDefaults['group_id'];

        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('You have been successfully registered.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('We're unable register this user.'));
    }
}
}

You can't always remember default values set in the database if you've got about 60-80 tables with complicated relations.

AND

My advice is that you don't set defaults that depend on your current settings, be more flexible: create configuration table or set defaults in AppController in order to find it wth a blink of an eye.

Upvotes: 0

jwg2s
jwg2s

Reputation: 816

It would be better to set the default value in the database? I don't really see why you would want to do it CakePHP side...

Upvotes: 1

mark
mark

Reputation: 21743

you should always try to set default values from the controller: http://www.dereuromark.de/tag/default-values/

Upvotes: 1

Related Questions