Color swatches without creating palette images (configurable products)
I was using the entry at Adding Color Swatches to Configurable Products to add color swatches, but wanted to do two things:
- Change the position of the swatches so that they appear beneath the ‘Color’ dropdown
- Make it so that the store administrator didn’t have to create color swatch thumbnails in order to add a new color.
My solution is below. In order to create a color swatch, your custom attribute values simply need to have an Admin/backend label that looks like the following:
Dark Blue (#082F50)
The code below will strip out everything in the last parentheses and create a square <div> of that color to display the swatch. As long as you also add a frontend label, the customer will not see the color code.
Steps |
- Place the code below in app/design/frontend/default/my_theme_name/template/catalog/product/view/type/options/configurable.phtml
- Edit the $color_attributes array to contain all attribute codes that swatches are to be generated for
- Make sure your attribute value labels (on the “admin” side) look like: Dark Red (#990101), where the item in parentheses is the hex code for the color
- <?php
- $_product = $this->getProduct();
- $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
- ?>
- <?php if ($_product->isSaleable() && count($_attributes)):?>
- <dl>
- <?php foreach($_attributes as $_attribute): ?>
- <dt><label><?php echo $_attribute->getLabel() ?><span class="required"> *</span></label></dt>
- <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
- <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
- <option><?php echo $this->__('Choose an Option...') ?></option>
- </select>
- </dd>
- <?php
- $_productAttribute = $_attribute->getProductAttribute();
- $_option_vals = array();
- //
- // The following is an array of attribute codes.
- // List here all attributes that will potentially
- // have associated color codes
- //
- $color_attributes = array('bag_color');
- if ( in_array($_productAttribute->getAttributeCode(), $color_attributes) ) {
- echo '<div><ul>';
- $_colors = array();
- //
- // Pull in all potential options for this attribute
- //
- $_collection = Mage::getResourceModel('eav/entity_attribute_option_collection')
- ->setStoreFilter(0)
- ->setAttributeFilter($_productAttribute->getId())
- ->load();
- foreach( $_collection->toOptionArray() as $_cur_option ) {
- $_option_vals[$_cur_option['value']] = array('id' => $_cur_option['value'], 'internal_label' => $_cur_option['label']);
- }
- //
- // Get associated products
- //
- $temp = new Mage_Catalog_Block_Product_View_Type_Configurable();
- $_assProducts = Mage::helper('core')->decorateArray($temp->getAllowProducts());
- foreach($_assProducts as $_assProduct){
- $_tempProduct = Mage::getModel('catalog/product');
- $_tempProduct->load($_assProduct->getId());
- $_option_id = $_tempProduct->getData($_productAttribute->getAttributeCode());
- //
- // Keep track of the admin/backend label for this option id
- //
- if ( isset($_option_vals[$_option_id]['internal_label']) ) {
- $_option_vals[$_option_id]['label'] = $_tempProduct->getAttributeText($_productAttribute->getAttributeCode());
- array_push($_colors, $_option_id);
- }
- }
- $_color_swatch = array_unique($_colors);
- foreach($_color_swatch as $_inner_option_id){
- preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches);
- if ( count($matches[0]) > 0 ) {
- //
- // Found a color definition in the admin label
- //
- $color_value = $matches[1][count($matches[0])-1];
- echo '<li><div onclick="set_attribute_selected_value('.$_attribute->getAttributeId().', '.$_inner_option_id.');" style="cursor:pointer; float:left; margin-left: 8px; height: 32px; width: 32px; background-color: '.$color_value.';"> </div></li>';
- }
- }
- echo '</ul></div>';
- }
- endforeach;
- ?>
- </dl>
- <script type="text/javascript">
- var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
- function set_attribute_selected_value( attribute_id, val ) {
- dropdown = document.getElementById('attribute' + attribute_id);
- for ( var i = 0; i < dropdown.options.length; i++ ) {
- if ( dropdown.options[i].value == val ) {
- dropdown.selectedIndex = i;
- break;
- }
- }
- spConfig.configureElement($('attribute' + attribute_id));
- }
- </script>
- <?php endif;?>
Please feel free to contact me with any questions.
Introduction |
If you want to do the same as below with simple products, I made a simple piece of code to make it work easily and smoothly with jQuery. This is particularly useful on small projects where products don’t need to be an individual product. In my use case there weren’t any other product like this one and SKU wasn’t used.
Steps |
- Edit your product, go to Custom options tab and add a New Option Drop-down: http://grab.by/6qZU
Add as many color as you want and the SKU is consider as a color HEX.
- Place at the end of your file the code below in:
app/design/frontend/default/default/template/catalog/product/view/options/type/select.phtml
- <?php if($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN):?>
- <dt><label>Select your color</label></dt>
- <ul>
- <?php foreach ($_option->getValues() as $_value) { ?>
- <li class="colorpick <?php echo str_replace(" ","_",$_value->getid()) ?>" style="background-color:#<?php echo $_value->getSku(); ?>;"> </li>
- <?php } ?>
- </ul>
- <script src="http://code.jquery.com/jquery-latest.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function(){
- $(".colorpick").click(function() {
- var id = this.className.split(' ')[1];
- $("select[name='options[<?php echo $_option->getid() ?>]']").val(id);
- if($(".colorpick").hasClass('highlight')) {
- $(".colorpick").removeClass('highlight');
- }
- $(this).addClass('highlight');
- });
- $("select[name='options[<?php echo $_option->getid() ?>]']").change(function() {
- var selected_option = $("select[name='options[<?php echo $_option->getid() ?>]']").val();
- if($(".colorpick").hasClass('highlight')) {
- $(".colorpick").removeClass('highlight');
- }
- $("."+selected_option).addClass('highlight');
- });
- });
- </script>
- <?php endif; ?>
- add a some CSS to stylish your color boxes:
- .highlight { border: 2px solid #000; }
- .colorpick { cursor:pointer; width:20px; height:20px; float:left; margin:1px; display:inline; vertical-align: middle; }
Final result |



