views:

684

answers:

1

I have a field called Hobbies, I wish to store all the hobbies selected by the user to be stored in the database as CSV. How can I do this in Cakephp?

+2  A: 

Paste into view (ie, views/users/add.ctp)

<?php echo $form->create('User', array('action' => 'add')) ?>
<?php echo $form->input('User.hobbies', array('type' => 'select',
                                              'multiple' => 'checkbox',
                                              'options' => array('sports' => 'sports',
                                                                 'movies' => 'movies',
                                                                 'games' => 'games'))) ?>
<?php echo $form->end('Save') ?>

Paste into Users controller (just a standard save method, nothing special here)

function add() {
    if(!empty($this->data)) {
    if($this->User->saveAll($this->data, array('validate' => 'first'))) {
        $this->Session->setFlash('User saved successfully');
        } else {
        $this->Session->setFlash('User failed to save');
        }
    }
}

Paste into User model

function beforeValidate() {
    // join hobbies into csv
    if(!empty($this->data['User']['hobbies'])) {
        $this->data['User']['hobbies'] = join(',', $this->data['User']['hobbies']);
    }

    return true;
}

Notes:

  • If you need to separate the hobbies back out when reading the User model, you could use the "afterFind" callback or check out the Serializable Behaviour http://blog.matsimitsu.nl/code/206/serializeable-behavior-for-cakephp that automatically serializes and deserializes whenever you try to add or pull out an array to/from the db.
  • You could add the beforeValidate code to the beforeSave callback instead, just depends what kind of validation you want to perform. having the code in beforeValidate will let you do a basic notEmpty check, however in beforeSave will mean you can check individual items are present in the array.

References:

Benjamin Pearson