2014-12-03 14 views
11

Nuova installazione di Magento 1.9.1.Magento 1.9.1 non ordinamento elenco a discesa degli attributi di prodotto configurabili per posizione

Magento ignora la posizione dell'attributo impostata in Catalogue-> Attributes-> Manage Attributes-> Manage Labels/Options per un prodotto configurabile a discesa. Invece sta usando l'ID prodotto per determinare l'ordine della lista.

Hanno confrontato i seguenti file/funzioni e, a parte un piccolo calcolo delle imposte, nessuno del codice è stato modificato da 1.7.0.2.

Mage/Catalogo/modello/prodotto/tipo/Configuarable.php:

public function getConfigurableAttributes($product = null) 

Mage/Catalogo/modello/prodotto/Option.php:

public function getProductOptionCollection(Mage_Catalog_Model_Product $product) 

Mage/Catalogo/blocchi/prodotto/Vista/tipo/Configuarable.php:

public function getJsonConfig() 

ho anche testato su un database copia di un sito dal vivo e tutto l'ordinamento attributo si basa su Codice prodotto.

Per replicare.

  1. Creare un attributo - Colore

  2. Aggiungere etichette - nero, rosso, verde, blu

  3. Salva attributo.

  4. Creare prodotti associati configurabili e semplici con gli attributi nell'ordine precedente.

Modificare l'attributo e modificare le posizioni dell'etichetta. Blu 0, Verde 1, Rosso 3, Nero 4

Durante la visualizzazione del prodotto, Magento ordina ancora gli attributi in base all'ID prodotto e ignora le posizioni.

+0

fa qualcuno ha qualche idea su come riportare l'ordinamento in posizione? – hejhog

risposta

14

La risposta di Meogi funziona ma non è la risposta perfetta in quanto selezionerà solo le opzioni sul frontend. Prova a creare un ordine dal pannello di amministrazione per un prodotto configurabile. Otterrai comunque l'elenco di opzioni degli attributi erroneamente ordinati.

Invece, è possibile copiare app/codice/core/Mago/Catalogo/Modello/Risorsa/Prodotto/Tipo/Configurabile/Attributo/Collezione.php all'app cartella locale/codice/locale/Mago/Catalogo/Modello/Risorsa /Product/Type/Configurable/Attribute/Collection.php e applicare questa patch:

Index: app/code/local/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
=================================================================== 
--- app/code/local/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
+++ app/code/local/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
@@ -301,7 +301,28 @@ 
        } 
       } 
      } 

+   /** 
+    * Mage 1.9+ fix for configurable attribute options not sorting to position 
+    * @author Harshit <[email protected]> 
+    */ 
+   $sortOrder = 1; 
+   foreach ($this->_items as $item) { 
+    $productAttribute = $item->getProductAttribute(); 
+    if (!($productAttribute instanceof Mage_Eav_Model_Entity_Attribute_Abstract)) { 
+     continue; 
+    } 
+    $options = $productAttribute->getFrontend()->getSelectOptions(); 
+    foreach ($options as $option) { 
+     if (!$option['value']) { 
         continue; 
        } 

+     if (isset($values[$item->getId() . ':' . $option['value']])) { 
+      $values[$item->getId() . ':' . $option['value']]['order'] = $sortOrder++; 
+     } 
+    } 
+   } 
+   usort($values, function ($a, $b) { 
+    return $a['order'] - $b['order']; 
+   }); 
+    
      foreach ($values as $data) { 
       $this->getItemById($data['product_super_attribute_id'])->addPrice($data); 
      } 

Se siete titubanti di copia in un file core a cartella locale allora posso creare un modulo rapido, <rewrite> questo Collection.php file e basta sovrascrivere la funzione _loadPrices() e introdurre questa correzione.

+2

Ho patchato il file e creato una panoramica per quelli di voi che non sanno come fare questo http://magentosupport.help/knowledgebase/solved-sort-configurable-product-attribute-options-and-dropdowns/ –

+0

Lì [è anche una risposta qui] (http://magento.stackexchange.com/a/76090/14992) che fa qualcosa di simile a questo, ma in un modulo locale piuttosto che una sovrascrittura basata su file –

+3

@Harshit, grazie per la soluzione. L'ho messo in un modulo [qui] (https://github.com/rossmc/SwatchSorting) per chiunque lo desideri. – Holly

7

Avviso: La soluzione illustrata qui estende un file di classe di blocco nella libreria principale di Magento. Ho esaminato il codice sorgente di Magento prima di questo approccio e ho stabilito che non c'era un buon evento da osservare per evitare questo approccio. Se in una versione futura di Magento questo problema di ordinamento viene risolto, puoi annullare queste modifiche di seguito semplicemente disattivando l'estensione nel suo file app/etc/modules XML.

Fase 1: creare il file app/etc/modules/FirstScribe_CatalogOptionSortFix.xml

Contenuto:

<?xml version="1.0"?> 
<config> 
    <modules> 
     <FirstScribe_CatalogOptionSortFix> 
      <active>true</active> 
      <codePool>local</codePool> 
      <depends> 
       <Mage_Catalog /> 
      </depends> 
     </FirstScribe_CatalogOptionSortFix> 
    </modules> 
</config> 

Nota: Per il passaggio 2 e 3, creare directory per questi file se necessario. Ad esempio, potresti già disporre della directory app/code/local oppure, in base alle estensioni che hai già installato sul tuo sito, non è possibile.

Fase 2: Creare il file app/code/local/FirstScribe/CatalogOptionSortFix/etc/config.xml

Contenuto:

<?xml version="1.0"?> 
<!-- 
/** 
* Magento 1.9.1.0 has a bug in that the configurable options are sorted by 
* ID rather than position for the Configurable Product's front end view script. 
* This extension addresses this problem. 
* 
* @category FirstScribe 
* @package  FirstScribe_CatalogOptionSortFix 
* @version  2014.12.15 
*/ 
--> 
<config> 
    <modules> 
     <FirstScribe_CatalogOptionSortFix> 
      <version>1.0.0</version> 
     </FirstScribe_CatalogOptionSortFix> 
    </modules> 
    <global> 
     <blocks> 
      <catalog> 
       <rewrite> 
        <product_view_type_configurable>FirstScribe_CatalogOptionSortFix_Block_Product_View_Type_Configurable</product_view_type_configurable> 
       </rewrite> 
      </catalog> 
     </blocks> 
    </global> 
</config> 

Fase 3: Creare il file app/code/local/FirstScribe/CatalogOptionSortFix/Block/Prodotto/Visualizza/Tipo/Configurable.php

Contenuto:

<?php 
/** 
* Magento 1.9.1.0 has a bug in that the configurable options are sorted by 
* ID rather than position for the Configurable Product's front end view script. 
* This extension addresses this problem. 
* 
* @category FirstScribe 
* @package  FirstScribe_CatalogOptionSortFix 
* @version  2014.12.15 
*/ 
class FirstScribe_CatalogOptionSortFix_Block_Product_View_Type_Configurable extends Mage_Catalog_Block_Product_View_Type_Configurable 
{ 
    /** 
    * @var Magento_Db_Adapter_Pdo_Mysql 
    */ 
    protected $_read; 

    /** 
    * @var string 
    */ 
    protected $_tbl_eav_attribute_option; 

    /** 
    * Composes configuration for js 
    * 
    * @version 2014.12.15 - Addition of this line: 
    * $info['options'] = $this->_sortOptions($info['options']); 
    * 
    * @return string 
    */ 
    public function getJsonConfig() 
    { 
     $attributes = array(); 
     $options = array(); 
     $store  = $this->getCurrentStore(); 
     $taxHelper = Mage::helper('tax'); 
     $currentProduct = $this->getProduct(); 

     $preconfiguredFlag = $currentProduct->hasPreconfiguredValues(); 
     if ($preconfiguredFlag) { 
      $preconfiguredValues = $currentProduct->getPreconfiguredValues(); 
      $defaultValues  = array(); 
     } 

     foreach ($this->getAllowProducts() as $product) { 
      $productId = $product->getId(); 

      foreach ($this->getAllowAttributes() as $attribute) { 
       $productAttribute = $attribute->getProductAttribute(); 
       $productAttributeId = $productAttribute->getId(); 
       $attributeValue  = $product->getData($productAttribute->getAttributeCode()); 
       if (!isset($options[$productAttributeId])) { 
        $options[$productAttributeId] = array(); 
       } 

       if (!isset($options[$productAttributeId][$attributeValue])) { 
        $options[$productAttributeId][$attributeValue] = array(); 
       } 
       $options[$productAttributeId][$attributeValue][] = $productId; 
      } 
     } 

     $this->_resPrices = array(
      $this->_preparePrice($currentProduct->getFinalPrice()) 
     ); 

     foreach ($this->getAllowAttributes() as $attribute) { 
      $productAttribute = $attribute->getProductAttribute(); 
      $attributeId = $productAttribute->getId(); 
      $info = array(
        'id'  => $productAttribute->getId(), 
        'code'  => $productAttribute->getAttributeCode(), 
        'label'  => $attribute->getLabel(), 
        'options' => array() 
      ); 

      $optionPrices = array(); 
      $prices = $attribute->getPrices(); 
      if (is_array($prices)) { 
       foreach ($prices as $value) { 
        if(!$this->_validateAttributeValue($attributeId, $value, $options)) { 
         continue; 
        } 
        $currentProduct->setConfigurablePrice(
          $this->_preparePrice($value['pricing_value'], $value['is_percent']) 
        ); 
        $currentProduct->setParentId(true); 
        Mage::dispatchEvent(
          'catalog_product_type_configurable_price', 
          array('product' => $currentProduct) 
        ); 
        $configurablePrice = $currentProduct->getConfigurablePrice(); 

        if (isset($options[$attributeId][$value['value_index']])) { 
         $productsIndex = $options[$attributeId][$value['value_index']]; 
        } else { 
         $productsIndex = array(); 
        } 

        $info['options'][] = array(
          'id'  => $value['value_index'], 
          'label'  => $value['label'], 
          'price'  => $configurablePrice, 
          'oldPrice' => $this->_prepareOldPrice($value['pricing_value'], $value['is_percent']), 
          'products' => $productsIndex, 
        ); 
        $optionPrices[] = $configurablePrice; 
       } 
      } 

      // CALL SORT ORDER FIX 
      $info['options'] = $this->_sortOptions($info['options']); 

      /** 
      * Prepare formated values for options choose 
      */ 
      foreach ($optionPrices as $optionPrice) { 
       foreach ($optionPrices as $additional) { 
        $this->_preparePrice(abs($additional-$optionPrice)); 
       } 
      } 
      if($this->_validateAttributeInfo($info)) { 
       $attributes[$attributeId] = $info; 
      } 

      // Add attribute default value (if set) 
      if ($preconfiguredFlag) { 
       $configValue = $preconfiguredValues->getData('super_attribute/' . $attributeId); 
       if ($configValue) { 
        $defaultValues[$attributeId] = $configValue; 
       } 
      } 
     } 

     $taxCalculation = Mage::getSingleton('tax/calculation'); 
     if (!$taxCalculation->getCustomer() && Mage::registry('current_customer')) { 
      $taxCalculation->setCustomer(Mage::registry('current_customer')); 
     } 

     $_request = $taxCalculation->getDefaultRateRequest(); 
     $_request->setProductClassId($currentProduct->getTaxClassId()); 
     $defaultTax = $taxCalculation->getRate($_request); 

     $_request = $taxCalculation->getRateRequest(); 
     $_request->setProductClassId($currentProduct->getTaxClassId()); 
     $currentTax = $taxCalculation->getRate($_request); 

     $taxConfig = array(
       'includeTax'  => $taxHelper->priceIncludesTax(), 
       'showIncludeTax' => $taxHelper->displayPriceIncludingTax(), 
       'showBothPrices' => $taxHelper->displayBothPrices(), 
       'defaultTax'  => $defaultTax, 
       'currentTax'  => $currentTax, 
       'inclTaxTitle'  => Mage::helper('catalog')->__('Incl. Tax') 
     ); 

     $config = array(
       'attributes'  => $attributes, 
       'template'   => str_replace('%s', '#{price}', $store->getCurrentCurrency()->getOutputFormat()), 
       'basePrice'   => $this->_registerJsPrice($this->_convertPrice($currentProduct->getFinalPrice())), 
       'oldPrice'   => $this->_registerJsPrice($this->_convertPrice($currentProduct->getPrice())), 
       'productId'   => $currentProduct->getId(), 
       'chooseText'  => Mage::helper('catalog')->__('Choose an Option...'), 
       'taxConfig'   => $taxConfig 
     ); 

     if ($preconfiguredFlag && !empty($defaultValues)) { 
      $config['defaultValues'] = $defaultValues; 
     } 

     $config = array_merge($config, $this->_getAdditionalConfig());  

     return Mage::helper('core')->jsonEncode($config); 
    } 

    /** 
    * Sort the options based off their position. 
    * 
    * @param array $options 
    * @return array 
    */ 
    protected function _sortOptions($options) 
    { 
     if (count($options)) { 
      if (!$this->_read || !$this->_tbl_eav_attribute_option) { 
       $resource = Mage::getSingleton('core/resource'); 

       $this->_read = $resource->getConnection('core_read'); 
       $this->_tbl_eav_attribute_option = $resource->getTableName('eav_attribute_option'); 
      } 

      // Gather the option_id for all our current options 
      $option_ids = array(); 
      foreach ($options as $option) { 
       $option_ids[] = $option['id']; 

       $var_name = 'option_id_'.$option['id']; 
       $$var_name = $option; 
      } 

      $sql = "SELECT `option_id` FROM `{$this->_tbl_eav_attribute_option}` WHERE `option_id` IN('".implode('\',\'', $option_ids)."') ORDER BY `sort_order`"; 
      $result = $this->_read->fetchCol($sql); 

      $options = array(); 
      foreach ($result as $option_id) { 
       $var_name = 'option_id_'.$option_id; 
       $options[] = $$var_name; 
      } 
     } 

     return $options; 
    } 
} 

Fase 4: Se abilitata, rinfrescano "Configurazione" tipo di cache di Magento in Sistema -> Gestione della cache del pannello di amministrazione.

panoramica estensione

  1. estendere la classe Mage_Catalog_Block_Product_View_Type_Configurable.
  2. Aggiungere un metodo per ordinare le opzioni con il loro valore position estraendo queste informazioni dal database.
  3. Riscrivere il metodo getJsonConfig per chiamare la nostra nuova funzione dopo aver raccolto le opzioni per un attributo.
+0

Questa risposta è corretta e funziona perfettamente, grazie. Spero che non causi problemi una volta rilasciato un aggiornamento ufficiale ... Sono sorpreso che non ci sia stato molto di più fuori sul tema. – Joe

+2

@Joe Benvenuto. Feedback sugli aggiornamenti - la soluzione è scritta in modo tale che una volta che il core team di Magento risolve il problema in un aggiornamento, tutto ciò che dobbiamo fare è disabilitare questa estensione in 'app/etc/modules/FirstScribe_CatalogOptionSortFix.xml' e tutto tornerà usare le classi core di Mage, non più riscrivere le core classes. – Meogi

+0

Ho seguito le tue istruzioni e funziona perfettamente sulla pagina del prodotto. I campioni di colore sulla pagina di elenco degli articoli sono ancora fuori uso. Avete consigli? – tzvi

0

Sostituire la raccolta di attributi e aggiungere le modifiche al codice come di seguito. Questo risolverà il problema di ordinamento e anche il problema del caricamento di valori di opzioni elevate. "L'usort sta dando problema riguarda i prezzi, così ha commentato fuori"

<?php 
class Custom_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection extends Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection { 

    protected static $_pricings = array(); 

    protected function _loadPrices() { 
     if ($this->count()) { 
      $pricings = array(
       0 => array() 
      ); 

      if ($this->getHelper()->isPriceGlobal()) { 
       $websiteId = 0; 
      } else { 
       $websiteId = (int)Mage::app()->getStore($this->getStoreId())->getWebsiteId(); 
       $pricing[$websiteId] = array(); 
      } 

      $select = $this->getConnection()->select() 
       ->from(array('price' => $this->_priceTable)) 
       ->where('price.product_super_attribute_id IN (?)', array_keys($this->_items)); 

      if ($websiteId > 0) { 
       $select->where('price.website_id IN(?)', array(0, $websiteId)); 
      } else { 
       $select->where('price.website_id = ?', 0); 
      } 

      $query = $this->getConnection()->query($select); 

      while ($row = $query->fetch()) { 
       $pricings[(int)$row['website_id']][] = $row; 
      } 

      $values = array(); 

      //custom codes 
      if (!Mage::app()->getStore()->isAdmin() && isset(self::$_pricings[$this->getProduct()->getId()])) { 
       $values = self::$_pricings[$this->getProduct()->getId()]; 

      } else {//custom codes 
       foreach ($this->_items as $item) { 
        $productAttribute = $item->getProductAttribute(); 
        if (!($productAttribute instanceof Mage_Eav_Model_Entity_Attribute_Abstract)) { 
         continue; 
        } 
        $options = $productAttribute->getFrontend()->getSelectOptions(); 

        $optionsByValue = array(); 
        $sortOrders = array(); //custom codes 
        $sortOrder = 1; //custom codes 
        foreach ($options as $option) { 
         $optionsByValue[$option['value']] = $option['label']; 
         $sortOrders[$option['value']] = $sortOrder++; //custom codes 
        } 

        foreach ($this->getProduct()->getTypeInstance(true) 
           ->getUsedProducts(array($productAttribute->getAttributeCode()), $this->getProduct()) 
          as $associatedProduct) { 

         $optionValue = $associatedProduct->getData($productAttribute->getAttributeCode()); 

         if (array_key_exists($optionValue, $optionsByValue)) { 
          // If option available in associated product 
          if (!isset($values[$item->getId() . ':' . $optionValue])) { 
           // If option not added, we will add it. 
           $values[$item->getId() . ':' . $optionValue] = array(
            'product_super_attribute_id' => $item->getId(), 
            'value_index'    => $optionValue, 
            'label'      => $optionsByValue[$optionValue], 
            'default_label'    => $optionsByValue[$optionValue], 
            'store_label'    => $optionsByValue[$optionValue], 
            'is_percent'     => 0, 
            'pricing_value'    => null, 
            'use_default_value'   => true, 
            'sort_order'     => $sortOrders[$optionValue] //custom codes 
           ); 
          } 
         } 
        } 
       } 

       //custom codes 
       self::$_pricings[$this->getProduct()->getId()] = $values; 
       /**usort($values, function($a, $b) { 
        return $a['sort_order'] > $b['sort_order']; 
       });**/ 
      } 

      foreach ($pricings[0] as $pricing) { 
       // Addding pricing to options 
       $valueKey = $pricing['product_super_attribute_id'] . ':' . $pricing['value_index']; 
       if (isset($values[$valueKey])) { 
        $values[$valueKey]['pricing_value']  = $pricing['pricing_value']; 
        $values[$valueKey]['is_percent']  = $pricing['is_percent']; 
        $values[$valueKey]['value_id']   = $pricing['value_id']; 
        $values[$valueKey]['use_default_value'] = true; 
       } 
      } 

      if ($websiteId && isset($pricings[$websiteId])) { 
       foreach ($pricings[$websiteId] as $pricing) { 
        $valueKey = $pricing['product_super_attribute_id'] . ':' . $pricing['value_index']; 
        if (isset($values[$valueKey])) { 
         $values[$valueKey]['pricing_value']  = $pricing['pricing_value']; 
         $values[$valueKey]['is_percent']  = $pricing['is_percent']; 
         $values[$valueKey]['value_id']   = $pricing['value_id']; 
         $values[$valueKey]['use_default_value'] = false; 
        } 
       } 
      } 

      foreach ($values as $data) { 
       $this->getItemById($data['product_super_attribute_id'])->addPrice($data); 
      } 
     } 
     return $this; 
    } 

} 

sostituire la classe Mage_Catalog_Block_Product_View_Type_Configurable controllo per la funzione pubblica funzione di getJsonConfig() cambio $ prezzi = $ Attribute-> getPrices(); a $ prices = $ this -> _ sortPrices ($ attribute-> getPrices()); La funzione è la seguente

public function _sortPrices($prices) { 
    $sort_orders = array(); 
    $sorted_prices = array(); 
    foreach($prices as $key => $value) { 
     $sort_orders[$key] = $value['sort_order']; 
    } 
    asort($sort_orders); 

    foreach($sort_orders as $key => $value) { 
     $sorted_prices[] = $prices[$key]; 
    } 
    return $sorted_prices; 
} 
4

Giusto per aggiungere i miei due centesimi, le altre due risposte ha fatto bene a puntare nella direzione di correzione di me, ma ho pensato di attaccarlo alla fonte piuttosto che il punto di blocco presentazione .

è possibile ottenere lo stesso risultato, estendendo il metodo _loadPrices() il modello del Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection, che a dispetto del nome è dove è stato fatto un cambiamento (presumibilmente per le prestazioni) con conseguente gli attributi di essere ordinate per ID piuttosto che per importanza.

La modifica sembra essere stata effettuata per evitare le dichiarazioni nidificate foreach, ma a sua volta perde anche l'ordine corretto. Questa soluzione modifica leggermente la logica aggiornata per tenere traccia delle opzioni degli attributi, quindi esegue un altro ciclo basato sull'ordine originale per eseguire effettivamente l'aggiunta.

Ecco un walkthrough aggiustato simile a meogi's answer above:


Fase 1: Registra un nuovo modulo

Nota: se ne avete già uno, ri-usare uno esistente.

# File: app/etc/modules/YourCompany_AttributeFix.xml 
<?xml version="1.0"?> 
<config> 
    <modules> 
     <YourCompany_AttributeFix> 
      <active>true</active> 
      <codePool>local</codePool> 
      <depends> 
       <Mage_Catalog /> 
      </depends> 
     </YourCompany_AttributeFix> 
    </modules> 
</config> 

Passo 2: Creare la configurazione del modulo

# File: app/code/local/YourCompany/AttributeFix/etc/config.xml 
<?xml version="1.0"?> 
<config> 
    <modules> 
     <YourCompany_AttributeFix> 
      <version>0.1.0</version> 
     </YourCompany_AttributeFix> 
    </modules>  
    <global> 
     <models> 
      <catalog_resource> 
       <rewrite> 
        <product_type_configurable_attribute_collection>YourCompany_AttributeFix_Model_Resource_Product_Type_Configurable_Attribute_Collection</product_type_configurable_attribute_collection> 
       </rewrite> 
      </catalog_resource> 
     </models> 
    </global> 
</config> 

Fase 3: Aggiungere l'estensione modello di risorse

# File: app/code/local/YourCompany/AttributeFix/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
/** 
* Catalog Configurable Product Attribute Collection - overridden to re-enable the attribute option 
* sorting by relevance rather than by ID as changed in the Magento core class 
*/ 
class YourCompany_AttributeFix_Model_Resource_Product_Type_Configurable_Attribute_Collection 
    extends Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection 
{ 
    /** 
    * Load attribute prices information 
    * 
    * @return Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection 
    */ 
    protected function _loadPrices() 
    { 
     if ($this->count()) { 
      $pricings = array(
       0 => array() 
      ); 

      if ($this->getHelper()->isPriceGlobal()) { 
       $websiteId = 0; 
      } else { 
       $websiteId = (int)Mage::app()->getStore($this->getStoreId())->getWebsiteId(); 
       $pricing[$websiteId] = array(); 
      } 

      $select = $this->getConnection()->select() 
       ->from(array('price' => $this->_priceTable)) 
       ->where('price.product_super_attribute_id IN (?)', array_keys($this->_items)); 

      if ($websiteId > 0) { 
       $select->where('price.website_id IN(?)', array(0, $websiteId)); 
      } else { 
       $select->where('price.website_id = ?', 0); 
      } 

      $query = $this->getConnection()->query($select); 

      while ($row = $query->fetch()) { 
       $pricings[(int)$row['website_id']][] = $row; 
      } 

      $values = array(); 

      foreach ($this->_items as $item) { 
       $productAttribute = $item->getProductAttribute(); 
       if (!($productAttribute instanceof Mage_Eav_Model_Entity_Attribute_Abstract)) { 
        continue; 
       } 
       $options = $productAttribute->getFrontend()->getSelectOptions(); 

       $optionsByValue = array(); 
       foreach ($options as $option) { 
        $optionsByValue[$option['value']] = $option['label']; 
       } 

       /** 
       * Modification to re-enable the sorting by relevance for attribute options 
       * @author Robbie Averill <[email protected]> 
       */ 
       $toAdd = array(); 
       foreach ($this->getProduct()->getTypeInstance(true) 
          ->getUsedProducts(array($productAttribute->getAttributeCode()), $this->getProduct()) 
         as $associatedProduct) { 

        $optionValue = $associatedProduct->getData($productAttribute->getAttributeCode()); 

        if (array_key_exists($optionValue, $optionsByValue)) { 
         $toAdd[] = $optionValue; 
        } 
       } 

       // Add the attribute options, but in the relevant order rather than by ID 
       foreach (array_intersect_key($optionsByValue, array_flip($toAdd)) as $optionValueKey => $optionValue) { 
        // If option available in associated product 
        if (!isset($values[$item->getId() . ':' . $optionValue])) { 
         // If option not added, we will add it. 
         $values[$item->getId() . ':' . $optionValueKey] = array(
          'product_super_attribute_id' => $item->getId(), 
          'value_index'    => $optionValueKey, 
          'label'      => $optionsByValue[$optionValueKey], 
          'default_label'    => $optionsByValue[$optionValueKey], 
          'store_label'    => $optionsByValue[$optionValueKey], 
          'is_percent'     => 0, 
          'pricing_value'    => null, 
          'use_default_value'   => true 
         ); 
        } 
       } 
       /** 
       * End attribute option order modification 
       * @author Robbie Averill <[email protected]> 
       */ 
      } 

      foreach ($pricings[0] as $pricing) { 
       // Addding pricing to options 
       $valueKey = $pricing['product_super_attribute_id'] . ':' . $pricing['value_index']; 
       if (isset($values[$valueKey])) { 
        $values[$valueKey]['pricing_value']  = $pricing['pricing_value']; 
        $values[$valueKey]['is_percent']  = $pricing['is_percent']; 
        $values[$valueKey]['value_id']   = $pricing['value_id']; 
        $values[$valueKey]['use_default_value'] = true; 
       } 
      } 

      if ($websiteId && isset($pricings[$websiteId])) { 
       foreach ($pricings[$websiteId] as $pricing) { 
        $valueKey = $pricing['product_super_attribute_id'] . ':' . $pricing['value_index']; 
        if (isset($values[$valueKey])) { 
         $values[$valueKey]['pricing_value']  = $pricing['pricing_value']; 
         $values[$valueKey]['is_percent']  = $pricing['is_percent']; 
         $values[$valueKey]['value_id']   = $pricing['value_id']; 
         $values[$valueKey]['use_default_value'] = false; 
        } 
       } 
      } 

      foreach ($values as $data) { 
       $this->getItemById($data['product_super_attribute_id'])->addPrice($data); 
      } 
     } 
     return $this; 
    } 
} 

Fase 4: Svuota la cache


fo r di riferimento, il cambiamento reale alla classe di base in un git diff sarebbe inferiore (non modificare direttamente i file core!):

diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
index 135d9d3..4d2a59b 100644 
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable/Attribute/Collection.php 
@@ -254,6 +254,11 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection 
        $optionsByValue[$option['value']] = $option['label']; 
       } 

+    /** 
+     * Modification to re-enable the sorting by relevance for attribute options 
+     * @author Robbie Averill <[email protected]> 
+     */ 
+    $toAdd = array(); 
       foreach ($this->getProduct()->getTypeInstance(true) 
           ->getUsedProducts(array($productAttribute->getAttributeCode()), $this->getProduct()) 
          as $associatedProduct) { 
@@ -261,22 +266,31 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection 
        $optionValue = $associatedProduct->getData($productAttribute->getAttributeCode()); 

        if (array_key_exists($optionValue, $optionsByValue)) { 
-      // If option available in associated product 
-      if (!isset($values[$item->getId() . ':' . $optionValue])) { 
-       // If option not added, we will add it. 
-       $values[$item->getId() . ':' . $optionValue] = array(
-        'product_super_attribute_id' => $item->getId(), 
-        'value_index'    => $optionValue, 
-        'label'      => $optionsByValue[$optionValue], 
-        'default_label'    => $optionsByValue[$optionValue], 
-        'store_label'    => $optionsByValue[$optionValue], 
-        'is_percent'     => 0, 
-        'pricing_value'    => null, 
-        'use_default_value'   => true 
-       ); 
-      } 
+      $toAdd[] = $optionValue; 
        } 
       } 
+ 
+    // Add the attribute options, but in the relevant order rather than by ID 
+    foreach (array_intersect_key($optionsByValue, array_flip($toAdd)) as $optionValueKey => $optionValue) { 
+     // If option available in associated product 
+     if (!isset($values[$item->getId() . ':' . $optionValue])) { 
+      // If option not added, we will add it. 
+      $values[$item->getId() . ':' . $optionValueKey] = array(
+       'product_super_attribute_id' => $item->getId(), 
+       'value_index'    => $optionValueKey, 
+       'label'      => $optionsByValue[$optionValueKey], 
+       'default_label'    => $optionsByValue[$optionValueKey], 
+       'store_label'    => $optionsByValue[$optionValueKey], 
+       'is_percent'     => 0, 
+       'pricing_value'    => null, 
+       'use_default_value'   => true 
+      ); 
+     } 
+    } 
+    /** 
+     * End attribute option order modification 
+     * @author Robbie Averill <[email protected]> 
+     */ 
      } 

      foreach ($pricings[0] as $pricing) { 

This is also on GitHub se qualcuno lo vuole per riferimento.

Modifica: Ho anche logged this as a bug with Magento.

+1

è fantastico .... Grazie a @Robbie –

+0

@MilanGajjar si prega di utilizzare il repository GitHub, ci sono state alcune correzioni di bug da questo post –

+0

Ho usato il tuo codice Git D: @Robbie –

Problemi correlati