Показаны сообщения с ярлыком Zend. Показать все сообщения
Показаны сообщения с ярлыком Zend. Показать все сообщения

среда, 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 следовательно если Вы решите обновить систему, то этот файл потрется. Не забудьте сделать копию предварительно.

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

четверг, 18 марта 2010 г.

Magento. Задать и получить Product QTY

Стоит следующая задача:

Задать и получить Product QTY.

Сначала попробовал сделать это через $product->getQty();

Но как оказалось все данные что связанные с Inventory хранятся в другой модели. Поэтому делаем так:

   $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId); 
   $stock->getQty(); // получаем QTY
   $stock->setQty(1); // задаем QTY
   $stock->save(); // Обязательно сохранись, если были внесены изменения

Собственно вот.

вторник, 22 декабря 2009 г.

Youtube API, Поиск по видео

Вот столкнулся недавно с задачей, поиска видео на Youtube из моего приложения.

Как оказалось задача проста. В Youtube Api с использованием PHP все вызовы идут с использованием Zend Framewokr.

Вот собственно функция для поиска видео:

function searchAndPrint($searchTerms)
{
  $yt = new Zend_Gdata_YouTube(); 
  $query = $yt->newVideoQuery();
  $query->setOrderBy('viewCount');
  $query->setRacy('include');
  $query->setVideoQuery($searchTerms);
  $videoFeed = $yt->getVideoFeed($query);
  printVideoFeed($videoFeed, 'Search results for: ' . $searchTerms);
}

Где функция вывода на экран (printVideoFeed):

function printVideoFeed($videoFeed, $displayTitle = null) 
{
  $count = 1;
  if ($displayTitle === null) {
    $displayTitle = $videoFeed->title->text;
  }
  echo '

' . $displayTitle . "

\n"; echo "
\n";
  foreach ($videoFeed as $videoEntry) {
    echo 'Entry # ' . $count . "\n";
    printVideoEntry($videoEntry);
    echo "\n";
    $count++;
  }
  echo "
\n"; }
 
 
function printVideoEntry($videoEntry, $tabs = "") 
{
  // the videoEntry object contains many helper functions that access the underlying mediaGroup object
  echo $tabs . 'Video: ' . $videoEntry->getVideoTitle() . "\n";
  echo $tabs . "\tDescription: " . $videoEntry->getVideoDescription() . "\n";
  echo $tabs . "\tCategory: " . $videoEntry->getVideoCategory() . "\n";
  echo $tabs . "\tTags: " . implode(", ", $videoEntry->getVideoTags()) . "\n";
  echo $tabs . "\tWatch page: " . $videoEntry->getVideoWatchPageUrl() . "\n";
  echo $tabs . "\tFlash Player Url: " . $videoEntry->getFlashPlayerUrl() . "\n";
  echo $tabs . "\tDuration: " . $videoEntry->getVideoDuration() . "\n";
  echo $tabs . "\tView count: " . $videoEntry->getVideoViewCount() . "\n";
  echo $tabs . "\tRating: " . $videoEntry->getVideoRatingInfo() . "\n";
  echo $tabs . "\tGeo Location: " . $videoEntry->getVideoGeoLocation() . "\n";
  
  // see the paragraph above this function for more information on the 'mediaGroup' object
  // here we are using the mediaGroup object directly to its 'Mobile RSTP link' child
 foreach ($videoEntry->mediaGroup->content as $content) {
    if ($content->type === "video/3gpp") {
      echo $tabs . "\tMobile RTSP link: " . $content->url . "\n";
    }
  }
  
  echo $tabs . "\tThumbnails:\n";
  $videoThumbnails = $videoEntry->getVideoThumbnails();

  foreach($videoThumbnails as $videoThumbnail) {
    echo $tabs . "\t\t" . $videoThumbnail['time'] . " - " . $videoThumbnail['url'];
    echo " height=" . $videoThumbnail['height'];
    echo " width=" . $videoThumbnail['width'];
    echo "\n";
  }
} 

Вот собственно и все. А дальше уже оформляйте вывод как вам нравится:). Удачи