Try the Demo

Magento

eCommerce Software for Online Growth

Color swatches without creating palette images (configurable products)

Last modified by shm123 on Wed, September 29, 2010 19:29
Source|Old Revisions  

I was using the entry at Adding Color Swatches to Configurable Products to add color swatches, but wanted to do two things:

  1. Change the position of the swatches so that they appear beneath the ‘Color’ dropdown
  2. 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

  1. Place the code below in app/design/frontend/default/my_theme_name/template/catalog/product/view/type/options/configurable.phtml
  2. Edit the $color_attributes array to contain all attribute codes that swatches are to be generated for
  3. 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
  1. <?php
  2. $_product    = $this->getProduct();
  3. $_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
  4. ?>
  5. <?php if ($_product->isSaleable() && count($_attributes)):?>
  6.     <dl>
  7.     <?php foreach($_attributes as $_attribute): ?>
  8.         <dt><label><?php echo $_attribute->getLabel() ?><span class="required">&nbsp;*</span></label></dt>
  9.         <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
  10.           <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
  11.             <option><?php echo $this->__('Choose an Option...') ?></option>
  12.           </select>
  13.         </dd>
  14.        
  15.     <?php
  16.         $_productAttribute = $_attribute->getProductAttribute();
  17.         $_option_vals = array();
  18.        
  19.  
  20.         //
  21.         // The following is an array of attribute codes.
  22.         // List here all attributes that will potentially
  23.         // have associated color codes
  24.         //
  25.         $color_attributes = array('bag_color');
  26.        
  27.        
  28.         if ( in_array($_productAttribute->getAttributeCode(), $color_attributes) ) {
  29.    
  30.                         echo '<div><ul>';
  31.  
  32.                         $_colors = array();
  33.  
  34.  
  35.                         //
  36.                         // Pull in all potential options for this attribute
  37.                         //
  38.                         $_collection = Mage::getResourceModel('eav/entity_attribute_option_collection')
  39.                                               ->setStoreFilter(0)
  40.                                                   ->setAttributeFilter($_productAttribute->getId())
  41.                                                     ->load();
  42.                
  43.                         foreach( $_collection->toOptionArray() as $_cur_option ) {
  44.                                $_option_vals[$_cur_option['value']] = array('id' => $_cur_option['value'], 'internal_label' => $_cur_option['label']);
  45.                            }
  46.  
  47.                         //
  48.                         // Get associated products
  49.                         //
  50.                         $tempnew Mage_Catalog_Block_Product_View_Type_Configurable();
  51.                         $_assProducts = Mage::helper('core')->decorateArray($temp->getAllowProducts());
  52.                        
  53.                         foreach($_assProducts as $_assProduct){
  54.  
  55.                                 $_tempProduct = Mage::getModel('catalog/product');
  56.                                 $_tempProduct->load($_assProduct->getId());
  57.            
  58.            
  59.                                 $_option_id = $_tempProduct->getData($_productAttribute->getAttributeCode());
  60.                
  61.  
  62.                                 //
  63.                                 // Keep track of the admin/backend label for this option id
  64.                                 //
  65.                                 if ( isset($_option_vals[$_option_id]['internal_label']) ) {
  66.                                     $_option_vals[$_option_id]['label'] = $_tempProduct->getAttributeText($_productAttribute->getAttributeCode());
  67.                                      array_push($_colors, $_option_id);
  68.                                 }
  69.  
  70.                                
  71.                         }
  72.  
  73.                         $_color_swatch = array_unique($_colors);
  74.  
  75.                         foreach($_color_swatch as $_inner_option_id){
  76.  
  77.                                  preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches);
  78.                                
  79.                                 if ( count($matches[0]) > 0 ) {
  80.        
  81.                                     //
  82.                                     // Found a color definition in the admin label
  83.                                     //
  84.                                     $color_value = $matches[1][count($matches[0])-1];
  85.  
  86.                                     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.';">&nbsp;</div></li>';
  87.                                 }
  88.  
  89.                         }
  90.  
  91.                         echo '</ul></div>';           
  92.                        
  93.         }
  94.    
  95.         endforeach;
  96.     ?>
  97.     </dl>
  98.    
  99.    <script type="text/javascript">
  100.         var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
  101.    
  102.         function set_attribute_selected_value( attribute_id, val ) {
  103.            
  104.             dropdown = document.getElementById('attribute' + attribute_id);
  105.            
  106.             for ( var i = 0; i < dropdown.options.length; i++ ) {
  107.                 if ( dropdown.options[i].value == val ) {
  108.                     dropdown.selectedIndex = i;
  109.                     break;
  110.                 }
  111.             }
  112.            
  113.             spConfig.configureElement($('attribute' + attribute_id));
  114.            
  115.         }
  116.     </script>
  117. <?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

  1. 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.

  1. Place at the end of your file the code below in:

app/design/frontend/default/default/template/catalog/product/view/options/type/select.phtml

  1. <?php if($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN):?>
  2. <dt><label>Select your color</label></dt>
  3. <ul>
  4. <?php foreach ($_option->getValues() as $_value) { ?>
  5. <li class="colorpick <?php echo str_replace(" ","_",$_value->getid()) ?>" style="background-color:#<?php echo $_value->getSku(); ?>;">&nbsp;</li>
  6. <?php } ?>
  7. </ul>
  8. <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  9. <script type="text/javascript">
  10. $(document).ready(function(){
  11.     $(".colorpick").click(function() {
  12.         var id = this.className.split(' ')[1];
  13.         $("select[name='options[<?php echo $_option->getid() ?>]']").val(id);
  14.         if($(".colorpick").hasClass('highlight')) {
  15.             $(".colorpick").removeClass('highlight');
  16.         }
  17.         $(this).addClass('highlight');
  18.     });
  19.     $("select[name='options[<?php echo $_option->getid() ?>]']").change(function() {
  20.         var selected_option = $("select[name='options[<?php echo $_option->getid() ?>]']").val();       
  21.         if($(".colorpick").hasClass('highlight')) {
  22.             $(".colorpick").removeClass('highlight');
  23.         }
  24.         $("."+selected_option).addClass('highlight');
  25.     });
  26. });
  27. </script>
  28. <?php endif; ?>
  1. add a some CSS to stylish your color boxes:
  1. .highlight { border: 2px solid #000; }
  2. .colorpick { cursor:pointer; width:20px; height:20px; float:left; margin:1px; display:inline; vertical-align: middle; }

Final result




 

Introducing Magento Go

Magento Job Board - Some sort of tag line goes here

Latest Posts| View all Jobs
© Copyright 2012 Magento Inc.
Privacy Policy|Terms of Service
Magento Community Count
701238 users|825 users currently online|497303 forum posts