简体   繁体   中英

Magento : Get product configurable options on category page

In the category listing page on my Magento site, I've a column on that right that loads the product's view page thru AJAX when a user clicks on a product. I'm able to retrieve all content from the view page like images, tabs etc, but I'm not able to retrieve the product's configurable options because they're stored as a javascript variable.

Any ideas on how I can retrieve that info as well?

Edit - Better explanation: I'm trying to let the user configure the product right from the category page, by showing them all the options without having to navigate to each product's view page. So far, I've only been able to get the html but the dropdowns are empty. And thats because all the options & their prices are stored as a javascript variable in the view page. So my question is, how do i get those options thru an ajax call & load the dropdowns & have them work exactly the way they do in the product view page?

Magento uses JS, it is true. It uses Mage_Catalog_Block_Product_View_Type_Configurable class to render configurable products. And you shoulda be interested in its getJsonConfig() method. It is used within the app/design/frontend/base/default/template/catalog/product/view/type/options/configurable.phtml template to render the javascript code which does the magick, as you said.

So, in the template it looks like:

<script type="text/javascript">
    var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>

In the browser it looks like:

<script type="text/javascript">
    var denyProduct = {"62":["12","9"]}        
    var spConfig = new Product.Config({"attributes":{"70":{"id":"70","code":"manufacturer","label":"Manufacturer","options":[{"id":"11","label":"Fischer","price":"10","oldPrice":"10","products":["61","66"]},{"id":"12","label":"Queen mum","price":"20","oldPrice":"20","products":["62"]}]},"122":{"id":"122","code":"size","label":"Maat","options":[{"id":"9","label":"M","price":"15","oldPrice":"15","products":["61","62"]},{"id":"10","label":"S","price":"0","oldPrice":"0","products":["66"]}]}},"template":"\u20ac\u00a0#{price}","basePrice":"150","oldPrice":"150","productId":"64","chooseText":"Kies een optie...","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":19,"currentTax":19,"inclTaxTitle":"Incl. BTW"}});
</script>

And the code which creates all that javascript options is ( Mage_Catalog_Block_Product_View_Type_Configurable::getJsonConfig() method):

$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'])
            );
            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->_preparePrice($value['pricing_value'], $value['is_percent']),
                'products'  => $productsIndex,
            );
            $optionPrices[] = $configurablePrice;
            //$this->_registerAdditionalJsPrice($value['pricing_value'], $value['is_percent']);
        }
    }
    /**
     * 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'));
}

And the code which connects those values to the <select> elements is located within the Product.js file.

If you just want to get all attributes, used within some category, here's the solution: assume you have a variable $_productCollection filled with category products. Then you can perform this performance-breaking code:

$setIds = array();

foreach ($_productCollection as $k => $product)
{
    $setIds[] = $product->getAttributeSetId();
}

/** @var $collection Mage_Catalog_Model_Resource_Product_Attribute_Collection */
$collection = Mage::getResourceModel('catalog/product_attribute_collection');
$collection
    ->setItemObjectClass('catalog/resource_eav_attribute')
    ->setAttributeSetFilter($setIds)
    ->addStoreLabel(Mage::app()->getStore()->getId())
    ->setOrder('position', 'ASC');

$collection->load();

So you shall get all the attributes (with repeats) within the $collection variable.

Hope, this will help you somehow.

This can take up considerable server resources as there can be many options for each product. Best way is to use ajax to only load ALL the options when asked for. I found this extension that will load colors first, then when you mouse over it will give you all the product options.

http://www.consofas.com/plugins/options-quickview-for-configurable-products-in-magento/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM