You are Here: Articles » Populating a CakePHP Form with MySQL Default Values.

Populating a CakePHP Form with MySQL Default Values.

Sometimes it can be handy to fill a form with defaults.

Tagged with Web Development and CakePHP
Posted on 12/9/09 by Paul Herron

Here's a quick tip for populating a form with the MySQL defaults. Take the following schema, for example, of editions of an email newsletter:

  1. DROP TABLE IF EXISTS editions;
  2.  
  3. CREATE TABLE editions (
  4.         id int(8) NOT NULL AUTO_INCREMENT,
  5.         title varchar(255) DEFAULT 'Coming up this week...',
  6.         created datetime DEFAULT NULL,
  7.         modified datetime DEFAULT NULL,
  8.         PRIMARY KEY (id)
  9. );

In this case, I'm taking the Edition.title field as one the user might want to change, but would most likely just use a default value for. Populating the form field with that default is simple using Model::create():

  1. <?php class EditionsController extends AppController {       function add() {         if(empty($this->data)) {                         $this->data = $this->Edition->create();               } else {                   if($this->Edition->save($this->data)) {                     $this->Session->setFlash('Edition saved.');          } else {         $this->Session->setFlash('Sorry. That edition could not be saved.');                      }           }    } } ?>

Leave a Comment

CAPTCHA[Refresh]

« Articles

Article Tags

Show all articles, or just those tagged as:

Feed

The articles RSS feed is available.

Elsewhom

See More…

Back to top.