среда, 17 августа 2011 г.

Magento: меняем фотографии товара, для Configurable продуктов

Сегодня попробуем сделать следующее:

Сделаем возможным, чтобы у Configurable продуктов менялись фотографии продуктов на странице с информацией при смене опции.

1) Откроем файл
app/design/frontend/*/*/template/catalog/product/view.phtml

Заменим


var optionsPrice = new Product.OptionsPrice(getJsonConfig() ?>);

на


var optionsPrice = new Product.OptionsPrice(getJsonConfig() ?>);
var assocIMG =  
getTypeId() == "configurable") {
        echo "{";
        $associated_products = $_product->loadByAttribute('sku', $_product->getSku())->getTypeInstance()->getUsedProducts();
        foreach ($associated_products as $assoc)
            $dados[] = $assoc->getId().":'".($assoc->image == "no_selection" || $assoc->image == "" ? $this->helper('catalog/image')->init($_product, 'image', $_product->image)->resize(365,400) : $this->helper('catalog/image')->init($assoc, 'image', $assoc->image)->resize(365,400))."'";
    } else {
        $dados[] =  "''";
    }
    echo implode(',', $dados );     
    if ($_product->getTypeId() == "configurable") {
        echo "}";
    }

2) Oткроем
app/design/frontend/*/*/template/catalog/product/view/type/options/configurable.phtml

Заменим

var spConfig = new Product.Config(getJsonConfig() ?>);

на

var spConfig = new Product.Config(getJsonConfig() ?>);
var selectedAssocProducts = {};


3) Файл
js/varien/configurable.js

a) Добавляем в самое начало файла

if(typeof selectedAssocProducts=='undefined') {
    var selectedAssocProducts = {};
}


b) В функцию configureElement : function(element), сразу после this.reloadPrice() добавляем


if (!element.value || element.value.substr(0,6) == 'choose') return; // Selected "choose option"
var attributeId = element.id.replace(/[a-z]*/, '');
for (var a in this.config.attributes)
{
    for (i = 0; i < this.config.attributes[a].options.length; i++)
    {
        if (this.config.attributes[a].options[i].id != element.value) continue;
        selectedAssocProducts[a] = this.config.attributes[attributeId].options[i].products;
    }
}
var productNo = intersect(selectedAssocProducts) || selectedAssocProducts[attributeId][0];
$('image').src = assocIMG[productNo];
c) Меняем метод resetChildren : function(element) на
resetChildren : function(element){
    delete selectedAssocProducts[element.config.id]; 
    if(element.childSettings) {       
        for(var i=0;i < element.childSettings.length;i++){
	    element.childSettings[i].selectedIndex = 0;
	    element.childSettings[i].disabled = true;               
	    delete selectedAssocProducts[element.childSettings[i].config.id]; 
	    if(element.config){
	        this.state[element.config.id] = false;                   
            }
        }
    }},
d) В конец файда добавляем:
function intersect(ar) // ar can be an array of arrays or an asssociative array
      {
          if (ar == null) return false;
          var a = new Array();
          if (ar.length == undefined) // Associate Array
          {       
              for (var i in ar)
               a.push(ar[i]);       
          }     
          else
           a = ar;
         
          if (a.length == 1) return false; // Single array ? Nothing to intersect with
          var common = new Array();
          function loop(a, index, s_index, e_index)
          {               
              if (index == null) index = 0;
              if (s_index == null) s_index = 0;
              if (e_index == null) e_index = a[index].length;
              if (index == a.length - 1) return;           
              for (var i = s_index; i < e_index; i++)
              {
                  if (common.indexOf(a[index][i]) != -1) continue;
                  for (var j = 0; j < a[index + 1].length; j++)
                  {
                      if (a[index][i] != a[index+1][j]) continue;                       
                      loop(a, index + 1, j, j + 1);
                      if (index + 1 == a.length - 1) { common.push(a[index][i]); break; }                       
                  }
              }           
          }       
          loop(a);
          return common;
      }

Сохраняем все. И готово.

Не забывайте! что мы правили js файл configurable.js следовательно если Вы решите обновить систему, то этот файл потрется. Не забудьте сделать копию предварительно.

Взято, ПРОВЕРЕНО, изменено и переведено отсюда 

понедельник, 15 августа 2011 г.

Открываем все внешние ссылки в новом окне. jQuery

Возникла задача, уже на существущем сайте, сделать так, чтобы все ссылки на внешние источники открывались в новом окне.

Чтобы сделать это быстро и с малыми трудозатратами, можно использовать следующий код, написанный на jQuery.



$(document).ready(function() { 
  $("a[href^=http]").each( //поиск всех "a" что имеют ссылки
    function(){
      if(this.href.indexOf(location.hostname) == -1) {
        $(this).attr('target', '_blank'); // и если host отличается от текущего, то перенапрявляем на новую страницу
      }
    })
});


Вот и все