Magento использует JS, это правда.Он использует класс Mage_Catalog_Block_Product_View_Type_Configurable
для визуализации настраиваемых продуктов.И вы должны быть заинтересованы в его getJsonConfig()
методе.Он используется в шаблоне app/design/frontend/base/default/template/catalog/product/view/type/options/configurable.phtml
для рендеринга кода javascript, который делает магию, как вы сказали.
Итак, в шаблоне это выглядит так:
<script type="text/javascript">
var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
</script>
В браузереэто выглядит так:
<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>
И код, который создает все эти параметры JavaScript, (Mage_Catalog_Block_Product_View_Type_Configurable::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'])
);
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'));
}
И код, который связывает эти значения с <select>
elements находится в файле Product.js
.
Если вы просто хотите получить все атрибуты, используемые в некоторой категории, вот решение: предположим, у вас есть переменная $_productCollection
, заполненная продуктами категории.Затем вы можете выполнить этот код, нарушающий производительность:
$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();
Таким образом, вы получите все атрибуты (с повторениями) в переменной $collection
.
Надеюсь, это вам как-то поможет.