Ketan Patel

How to Integrate Color Picker in CakePHP

Credit : Flickr


In many applications you might need to have color code as an input. For such case its recommended to have any color picker instead of plain input. There are many jquery plugins available for color picker. In this tutorial we'll see how to integrate color picker in CakePHP. Here we are going to use Farbtastic jquery color picker.




We have one Farbtastic Helper ready to use the Farbtastic in our cakephp application. In order to integrate the Farbtastic color picker just follow the given instructions.


Download Farbtastic


To get the farbtastic go to link : http://acko.net/dev/farbtastic and download the latest version of the Farbtastic and extract it.


(1) Copy the below images into your app/webroot/img folder.

       -- marker.png
       -- mask.png
       -- wheel.png


Now for show and hide button you need to get a colorpicker icon. Go to http://www.iconfinder.net/icondetails/5185/16/ and download image and save it as color.png,
and put it in your app/webroot/img/icon/ folder.


(2) Copy farbtastic.js file and put it into app/webroot/js folder.
(3) Copy farbtastic.css file and put it into app/webroot/css folder.
(4) Change the paths for the images from url(wheel.png) to url(../img/wheel.png) for all three images in farbtastic.css.


(5) Save the below code as FarbtasticHelper.php in app/View/Helper/ folder.

<?php 

/**
 *    Farbtastic helper
 *    @author     Curtis Gibby
 *    @desc       This helper does everything you need related to Farbtastic within CakePHP
 *
 *                Like Farbtastic, requires jQuery to function properly.
 *                jQuery: http://jquery.com
 *
 *                Also requires a Color Wheel icon (color.png in this example)
 *                like the one from Mark James' Silk set
 *                http://www.iconfinder.net/icondetails/5185/16/
 *
 *    @version    5 March 2010
 */

class FarbtasticHelper extends Helper  { 
    var $helpers = array('Javascript', 'Html');  

    /** 
    *    Add the JS/CSS to your header  
    *     
    */ 

    function includeHead() { 
        $str = ''; 
        $str .= $this->Html->script('farbtastic'); 
        $str .= $this->Html->css('farbtastic'); 
        return $str; 
    }

    /** 
    *    Generate a form input and related div and icon 
    *     
    *    may need to customize $icon_file (relative to webroot) 
    * 
    *    Adapted from April Hodge Silver's "Simple Colorpicker" input function 
    *    http://bakery.cakephp.org/articles/view/simple-colorpicker 
    */ 

    function input($name, $label='') { 
        $icon_file = '../img/icon/color.png'; // update to wherever your icon is. 
        list($model, $fieldname) = split('\.', $name); 

        if (empty($label)) { 
            $label = Inflector::Humanize($fieldname); 
        } 

        if(isset($this->data[$model][$fieldname])) { 

            $color_value = str_replace("#", "", $this->data[$model][$fieldname]); // expects an RGB string, strips any incoming '#' character 

        } 

        else { 
            $color_value = "000000"; // black 
        } 

      $str = ''; 
      $str .= '<div class="input text colorpicker">'; 
      $str .= '<label for="'.$model.Inflector::Camelize($fieldname).'">'.$label.'</label>';      $str .= '<input name="data['.$model.']['.$fieldname.']" type="text" maxlength="7" value="#'.$color_value.'" id="'.$model.Inflector::Camelize($fieldname).'" class="farbtastic-input" />'; 

      $str .= '<img id="farbtastic-picker-icon-'.Inflector::Camelize($fieldname).'" src="'.$icon_file.'" alt="Color Picker" title="Color Picker" class="farbtastic-picker-icon">'; 

      $str .= '<div style="display:none;" class="farbtastic-picker" id="farbtastic-picker-'.Inflector::Camelize($fieldname).'"></div>'; 

      $str .= '</div>'; 
      return $str; 
    } 

    /** 
    *    Add the jQuery magic to the $(document).ready function 
    *    Farbtastic-ize the input, make the button show/hide the color picker div 
    */
function readyJS($name) { 
        list($model,$fieldname) = split('\.',$name); 
        $str = ''; 
        $str .= ' $("#farbtastic-picker-'.Inflector::Camelize($fieldname).'").farbtastic("#'.$model.Inflector::Camelize($fieldname).'"); '; 
        $str .= ' $("#farbtastic-picker-icon-'.Inflector::Camelize($fieldname).'").click( function() { $("#farbtastic-picker-'.Inflector::Camelize($fieldname).'").toggle("slow"); }); '; 
       return $str; 
    } 
}?>



How to Use


Here I am explaining how to use this helper via simple example. For example we have sample table called 'fruits'.



/* First, create our fruits table: */
CREATE TABLE fruits (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    color CHAR(7)
);



We have our controller file called "FruitsController.php" with the below functions.


Note : Please note that we have included the Farbtastic in the helpers array.



<?php

class FruitsController extends AppController {

    public $helpers = array('Html', 'Form','Farbtastic');

    public function index() {
        $this->set('fruits', $this->Fruit->find('all'));
    }


   public function add() {
        if ($this->request->is('post')) {
            $this->Fruit->create();
            if ($this->Fruit->save($this->request->data)) {
                $this->Session->setFlash(__('Your record has been saved.'));
                return $this->redirect(array('action' => 'index'));
            }

            $this->Session->setFlash(__('Unable to add your record.'));
        }
    }

}

?>



Create one file "index.ctp" for listing of all the records.


<!-- File: /app/View/Fruits/index.ctp -->
<h1>Fruits</h1>
<table>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Color</th>
    </tr>
    <?php foreach ($fruits as $fruit): ?>
    <tr>
        <td><?php echo $fruit['Fruit']['id']; ?></td>
        <td><?php echo $fruit['Fruit']['name']; ?></td>
        <td><?php echo $fruit['Fruit']['color']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($fruit); ?>
</table>




Create one file "add.ctp" for adding new record.


<!-- File: /app/View/Fruits/add.ctp -->
<?php
        echo $this->Farbtastic->includeHead();
?>

<h1>Add Fruit</h1>
<?php
        echo $this->Form->create('Fruit');
        echo $this->Form->input('name');
        echo $this->Farbtastic->input('Fruit.color');
        echo $this->Form->end('Save Fruit');
?>

<script type="text/javascript" charset="utf-8">
 $(document).ready(function() {
        <?php  echo $this->Farbtastic->readyJS('Fruit.color');   ?>
    });
</script>



Please see that how the color input has been written.
        echo $this->Farbtastic->input('Fruit.color');


Now go to yoursite.com/fruits/add and you can see the color-picker integrated.!!!



Advantages of Farbtastic


-- Very easy integration
-- Its binding of color to input makes easy to know the selected color



Troubleshooting


If you want to change the name of the label for the color input then in normal cakephp way it should be written like,

        echo $this->Form->input('color',array('label'=>'yourlabel'));
     
but with Farbtastic input you should provide it without passing in array like,
     
        echo $this->Farbtastic->input('Fruit.color','yourlabel');




Thanks,
"Curtis Gibby - author of Farbtastic helper for cakephp" for making such useful helper. 

ketan patel

About Ketan Patel -

I have developed a wide range of websites using CorePHP, Opencart, CakePHP and CodeIgniter including sites for startup companies and small businesses. Apart from my blogging life, I like to read Novels, Listening music and Net surfing.

Subscribe to this Blog via Email :