A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

CakePHP: Select Box / Drop-down List linked from related Model

For example, an Article has an Author. In the database, the Article table would have an author_id field. Assuming that we are following the CakePHP Model and Database Conventions (http://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions), the models would look something like these:

<?php
## /Model/Article.php
App::uses('AuthComponent', 'Controller/Component');
 
class Article extends AppModel {
    public $name = 'Article';
 
    public $belongsTo = array(
        'Author' => array(
            'className' => 'Author',
            'foreignKey' => 'author_id'
        ),
    );
}

An Article that uses the articles table which belongs to an Author. The article table has a field named author_id. The author_id is linked to the id found in the author table.

The Author Model would be:

<?php
## /Model/Author.php
App::uses('AuthComponent', 'Controller/Component');
 
class Author extends AppModel {
    public $name = 'Author';
 
    public $hasMany = array(
        'Article' => array(
            'className' => 'Article',
            'foreignKey' => 'author_id'
        ),
    );
}

An Author uses the author table and has many Article. The article table has an author_id to link to it’s Author.

Now in one of my controllers, I would have a method that will allow me to add an Article and specify the Author. The Author field would be a dropdown / selectbox.

<?php
## /Controllers/ArticlesAdminController.php
//snip    
    public function add() {
        $this->layout = 'admin';
        $this->loadModel('Author');
        $this->loadModel('Article');
        $authors = $this->Author->find('list'); //we get the authors from the database
        $this->set('authors', $authors);
 
        if ($this->request->is('post')) {
            $this->Article->create();
            if ($this->Article->save($this->request->data)) {
                $this->Session->setFlash( __('The Article has been saved'), 'success');
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Article could not be saved. Please, try again'), 'error');
                //throw new InternalErrorException (__('The user could not be saved. Please, try again'));
            }
 
        }
    }

Finally, we have the view (/View/ArticlesAdmin/add.ctp).

 
<h1><?php echo __('Add Article'); ?></h1>
<?php
    echo $this->Form->create('Article', array('class' => 'well'));
 
    echo $this->Form->input('title', 
        array(
            'class' => 'span5',
            'after' => ' <span class="required_indicator">(required)</span> ',
            'error' => array('attributes' => array('wrap' => 'span', 'class' => 'label custom-inline-error label-important help-inline'))
        ));
 
    //the rest of the Article fields here...
 
    //The selectbox / dropdown menu for the Author field
    echo $this->Form->input('author_id', 
        array(
            'options' => $authors,
            'class' => 'span5',
            'error' => array('attributes' => array('wrap' => 'span', 'class' => 'label custom-inline-error label-important help-inline'))
        ));
 
?>
<?php echo $this->Form->end(__('Submit')) ?>
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>