Wednesday, November 17, 2010

How to handle variations with Javascript within Satchmo's product template

My goal was to list a set of variations on product page and redirect user to related product page if variation was changed. For example we have two variations:

  1. Size
  2. Colour
And values of variatons:
  1. Colour: red, black, white
  2. Size: M (middle), L (large), S (small)
So, first of all I display this variations on product page and when user change something (colour or size) then redirect to product with selected colour and size respectively.

1. Show dropdowns with variations:
{% for option_group in options %}

{% endfor %}

2. Store all possible variations for javascript to find related product if some of variations was changed on the page:
// list of available variations of current product
    var variations = [
    {% for product_variation in product.configurableproduct.productvariation_set.all %}{
        'url': '{{ product_variation.product.get_absolute_url }}',
        {% for option in product_variation.options.all %}
        'group-{{ option.option_group.id }}': '{{ option.value }}'{% if not forloop.last %},{% endif %}
        {% endfor %}
    }{% if not forloop.last %},{% endif %}{% endfor %}];

3. Add JavaScript code which will handle variations changes:
  /**
   * Select & go to variation which have been selected via select box.
   * This functionality require a set of available variations of the product
   * which consost from something like that: [
   * {'url': 'url_to_product', 'group-': '',..}
   * ]
   */
  var any = function(arr){
       for(var i = 0; i < arr.length; i++){
           if(arr[i] != true){
               return false;
           }
       }
       return true;
  }
  $('select.priced').bind('change', function(){
      var groups = {};
      $('select.priced').each(function(){
          if($(':selected', $(this))){
              groups[$(this).attr('id')] = $(this).val();
          }
      });

      $(variations).each(function(i, vr){
          var flags = [];
          
          for(var grp in groups){
              if(vr[grp] == groups[grp]){
                  flags.push(true)
              }else{
                  flags.push(false);
              }
          }
          
          if(any(flags)){
              location = vr['url'];
          }
      });
  });

No comments:

Post a Comment