Creating a Color Picker Field

Published on April 11, 2012 by in Back End

4

As we rapidly approach the launch of dotCMS 2.0, we’ve seen the addition of a number of new structure fields to the system since its launch. And there’s still more to come too – personally, I see a lot of potential in the generic Key/Value Pair field, which is very similar to custom fields in WordPress. However, you’ll almost certainly run into situations where you need a field that isn’t available. That’s where custom fields can be very helpful. In this tutorial, I’ll show you how to add a color picker field to a structure. Why a color picker? Why not? It’s a fast and easy way to allow customization of a theme, template or tool in the system, and can be helpful when trying to give users more options when they may not know how to find hex values.

Before I start, I should mention that Dojo has a color picker widget who’s library is included in dotCMS. But see, there’s two issues. One – I know jQuery better, so that’s what I’m using in this example, so just be aware that there is the extra script to load as a result. Two – I did try the Dojo color picker out, and got it mostly working, but the documentation for it isn’t very good and I simply couldn’t handle some of the use cases that I wanted to properly. So, jQuery all the way, and specifically, I’m using this color picker plugin. If anyone does it with Dojo and gets it working the same as here, I’d love to see it, since I’d prefer not load the extra JavaScript for jQuery if it’s avoidable.

Colorpicker Custom Field

Colorpicker Custom Field

In theory, by this point you caught that we’re going to use a custom field for this, so on your structure, go ahead and set one up. In this case, we’ll call it “Background Color.” We’ll then pull in jQuery, run noConflict() so that it won’t collide with Dojo in the back end, include the JS and CSS for the color picker, and apply it to a div. Additionally, you’ll see in the code I include a field called colorPickerField. This is so that you can manually control the color – and more specifically – unset the color if you don’t want it. Most of the color pickers don’t accept a null value for color, so if you rely just on the picker, then you will always have a value even if you don’t want one. If that’s not necessary in your case, by all means leave it out.

Since this is fairly straightforward, here’s all the code in one drop. The comments should pretty clearly explain what everything is doing. I also readily admit I’m not the world’s most awesome JavaScript ninja, so there may be some better ways to handle some of the stuff below. I’ll update code as people make recommendations.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/common/js/jquery/plugins/colorpicker/css/colorpicker.css" />
<style>
${esc.h}colorPicker {margin-bottom:1em;}
.colorpicker_submit,.colorpicker_hex {display:none;}
.invalid {background-color:${esc.h}ffcfcf;}
</style>
<script type="text/javascript" src="/common/js/jquery/plugins/colorpicker/js/colorpicker.js"></script>
<script>
// Make sure we don't screw up Dojo
jQuery.noConflict();
jQuery(document).ready(function() {
    // Regular expression for matching hex value
    var colorRxp = /[0-9A-Fa-f]{6}/

    jQuery('${esc.h}colorPicker').ColorPicker({
## SET OUR SELECTED COLOR IF USED
#if($UtilMethods.isSet($backgroundColor))
        color:'${esc.h}$!{backgroundColor}',
#end
        flat:true,
        onChange: function (hsb, hex, rgb) {
            // Save hex value to display field and storage field and remove warnings
            jQuery('${esc.h}backgroundColor').val(hex);
            jQuery('${esc.h}colorPickerField').removeClass('invalid');
            jQuery('${esc.h}colorPickerField').val(hex);
        }
    });

    // Set up our manual field
    jQuery('${esc.h}colorPickerField').keyup(function() {
        // Do we match the regex for a hex value?
        if(this.value.match(colorRxp)) {
            // Remove any warning color
            jQuery(this).removeClass("invalid");
            // Push color to color picker
            jQuery('${esc.h}colorPicker').ColorPickerSetColor(this.value);
            // Save value to storage field
            jQuery('${esc.h}backgroundColor').val(this.value);
        // Did we remove the color?
        } else if(this.value == "") {
            // Remove any warning color
            jQuery(this).removeClass("invalid");
            // Push white to the color picker (gotta give it something)
            jQuery('${esc.h}colorPicker').ColorPickerSetColor('ffffff');
            // Save a null to our storage field
            jQuery('${esc.h}backgroundColor').val('');
        // Otherwise, whatever is entered isn't a color
        } else {
            // Show a warning color on the field until it matches or is emptied
            jQuery(this).addClass("invalid");
        }
    });
});
</script>

<div id="colorPicker"></div>
<input type="text" id="colorPickerField" maxlength="6" value="$!{backgroundColor}" />
Picker Comparison

Top: Plain, unmodified usage. Bottom: Modified CSS to improve UI.

A couple other notes. I tweaked the CSS a little here to adjust things so that it made more sense in the context of our fields. So, you’ll note stuff like on lines 4 and 5 where I add some spacing and hide a couple tools. Also, in the screenshot up above the code, you’ll notice my colorpicker is light, while the normal one is dark. In the download, there’s a custom_background.png image that’s for lighter themes that you can switch to. I’ve also added in extra validation on our colorPickerField input so that we don’t send invalid color values to the picker.

Usage is simple. Either type in the hex value in the text box, which will update the color picker accordingly, or select a color in the picker, and it will set the value in the text box automatically. In this case, the extra validation will cause the text box to take on a red background if you type in a value that isn’t a valid hex color, and it won’t update the picker until you type one in correctly (I also apply the same regex to the field validation on the structure entry as well). In the  screenshot to the right, you can see I even adjusted the CSS further so that unlike the example above, my text box shows up inside the color picker, so it all feels like one nice, concise tool.

Hopefully this will give you some insight into just how easy it is to create unique types of custom fields that don’t already exist within dotCMS. If you have any questions, feel free to leave a comment below.


Photo credit: AttributionNoncommercialNo Derivative Works Some rights reserved by PhOtOnQuAnTiQuE

4 Responses to “Creating a Color Picker Field”

  1. Brad Rice says:

    Is there any difference between using custom fields for the backend than with a front end form? When I select custom field for a front end content form I just get a regular text input field regardless of the code I enter to have parsed.

  2. Michael Fienen says:

    I have not tested this on the front end yet, only the backend. It seems though that if the front end isn’t respecting the code of the custom field, then that’s probably a bug that needs to be logged.

  3. Marc Mathies says:

    I’m using Dojo with release 2.3.1 of DotCMS… works great. Here’s code

    var myCustomField = "colorSelector";
    dojo.require("dojox.widget.ColorPicker");
    var handler = function(val){
    dojo.byId(myCustomField).value = val;
    };
    document.write('');

Leave a Reply