Перечислите имя атрибута и значения для определенной группы
На странице списка продуктов я хотел бы, чтобы в списке маркеров внутри каждого продукта отображались имя и значение атрибута (для определенной группы - "Спецификация"), например
Спецификация
- Центры крепления: 120,6 мм
- Размер: 147,9 мм x 87,4 мм x 31 мм
Я уже добавил эти атрибуты и присвоил им значения в Magento. Используя приведенный ниже код (найден и изменен с помощью небольшого поиска здесь), я также могу вывести массив содержащий имя атрибута, однако я, похоже, не могу получить "интерфейсную" версию имени и значения:
$setId = $_product->getAttributeSetId(); // Attribute set Id
$groups = Mage::getModel('eav/entity_attribute_group')
->getResourceCollection()
->setAttributeSetFilter($setId)
->setSortOrder()
->load();
$attributeCodes = array();
foreach ($groups as $group) {
if($group->getAttributeGroupName() == 'Specification'){ // set name
//$groupName = $group->getAttributeGroupName();
//$groupId = $group->getAttributeGroupId();
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->setAttributeGroupFilter($group->getId())
->addVisibleFilter()
->checkConfigurableProducts()
->load();
if ($attributes->getSize() > 0) {
foreach ($attributes->getItems() as $attribute) {
/* @var $child Mage_Eav_Model_Entity_Attribute */
$attributeCodes[] = $attribute->getAttributeCode();
}
}
}
}
print_r($attributeCodes);
Вышеуказанные результаты Array ( [0] => mounting_box_depth [1] => fixing_centres [2] => size )
Чтобы получить значение, я попытался
$attributeValue = Mage::getModel('catalog/product')
->load($_product->getId())
->getAttributeText(attributeCodes[0]);
Но это, похоже, вообще ничего не возвращает. Есть какие-нибудь идеи?
В соответствии с просьбой, полностью перечислите файл.phtml ниже:
<?php
/**
* Product list template
*
* @see Mage_Catalog_Block_Product_List
*/
?>
<?php
$_productCollection=$this->getLoadedProductCollection();
$_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div class="category-products">
<?php //echo $this->getToolbarHtml() ?>
<?php // Grid Mode ?>
<?php $_collectionSize = $_productCollection->count() ?>
<?php $_columnCount = $this->getColumnCount(); ?>
<?php $i=0; foreach ($_productCollection as $_product): ?>
<?php if ($i++%$_columnCount==0): ?>
<ul class="products-grid">
<?php endif ?>
<li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
<div class="productBlock clearfix">
<?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
<div class="productBlock__compareLink plain-link">
<a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Compare this product') ?></a><a href="<?php echo $_product->getProductUrl() ?>" class="view blue-text">View</a>
<!-- .productBlock__compareLink --></div>
<?php endif; ?>
<div class="productBlock__image">
<a href="<?php echo $_product->getProductUrl() ?>" class="product-image"><img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(230); ?>" width="230" height="230" alt=""></a>
<!-- .productBlock__image --></div>
<div class="productBlock__description">
<h2 class="productBlock__description-name plain-link"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>
<div class="price-box-wrap">
<?php $promoType = strtolower($_product->getAttributeText('promo_type')); ?>
<?php if( stripos($promoType,'featured') !== false ) : ?>
<img class="is-featured" src="<?php echo $this->getSkinUrl('images/featured-product.png'); ?>" alt="<?php echo $this->__('Featured Product') ?>" width="121" height="45">
<?php endif; ?>
<?php echo $this->getPriceHtml($_product, true) ?>
<!-- .price-box --></div>
<ul class="check-list attribute-list">
<li><strong>Mounting Box Depth(Min):</strong> 25mm</li>
<li><strong>Fixing Centres:</strong> 120.6mm</li>
<li><strong>Size:</strong> 147.9mm x 87.4mm x 31mm</li>
<li><strong>Switch Type:</strong> Double Pole</li>
</ul>
<?php
$setId = $_product->getAttributeSetId(); // Attribute set Id
$groups = Mage::getModel('eav/entity_attribute_group')
->getResourceCollection()
->setAttributeSetFilter($setId)
->setSortOrder()
->load();
$attributeCodes = array();
foreach ($groups as $group) {
if($group->getAttributeGroupName() == 'Specification'){ // set name
//$groupName = $group->getAttributeGroupName();
//$groupId = $group->getAttributeGroupId();
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->setAttributeGroupFilter($group->getId())
->addVisibleFilter()
->checkConfigurableProducts()
->load();
if ($attributes->getSize() > 0) {
foreach ($attributes->getItems() as $attribute) {
/* @var $child Mage_Eav_Model_Entity_Attribute */
$attributeCodes[] = $attribute->getAttributeCode();
}
}
}
}
print_r($attributeCodes);
$attributeValue = Mage::getModel('catalog/product')
->load($_product->getId())
->getAttributeText($attributeCodes[0]);
echo "The value: " . $attributeValue;
?>
<!-- .productBlock__description --></div>
<div class="productBlock__actions">
<div class="productBlock__actions-shipping">
<div class="logos">
<img src="<?php echo $this->getSkinUrl('images/logo-british-general.png'); ?>" width="46" height="40" alt="">
</div>
<hr>
<h5>Free shipping</h5>
Lorem ipsum dolor sit amet
<!-- .productBlock__actions-shipping --></div>
<div class="productBlock__actions-buttons">
<hr>
<?php if($_product->isSaleable()): ?>
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button medium green btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Basket') ?></span></span></button>
<?php else: ?>
<p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
<?php endif; ?>
<ul class="add-to-links">
<li><a href="" class="link-compare button medium light-grey">More information</a></li>
</ul>
<!-- .productBlock__actions-buttons --></div>
<!-- .productBlock__actions --></div>
<!-- .productBlock --></div>
<!-- .item --></li>
<?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
</ul>
<?php endif ?>
<?php endforeach ?>
<script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
<div class="toolbar-bottom">
<?php //echo $this->getToolbarHtml() ?>
</div>
</div>
<?php endif; ?>
2 answers
Удалось получить желаемый результат с помощью следующего:
<?php
$setId = $_product->getAttributeSetId(); // Attribute set Id
$groups = Mage::getModel('eav/entity_attribute_group')
->getResourceCollection()
->setAttributeSetFilter($setId)
->setSortOrder()
->load();
$attributeCodes = array();
foreach ($groups as $group) {
if($group->getAttributeGroupName() == 'Specification'){ // set name
//$groupName = $group->getAttributeGroupName();
//$groupId = $group->getAttributeGroupId();
$attributes = Mage::getResourceModel('catalog/product_attribute_collection')
->setAttributeGroupFilter($group->getId())
->addVisibleFilter()
->checkConfigurableProducts()
->load();
if ($attributes->getSize() > 0) {
foreach ($attributes->getItems() as $attribute) {
/* @var $child Mage_Eav_Model_Entity_Attribute */
$attributeCodes[] = array('code' => $attribute->getAttributeCode(), 'type' => $attribute->getBackendType(), 'label' => $attribute->getFrontendLabel());
//Mage::Log($attribute->debug());
}
}
}
}
echo '<ul class="check-list attribute-list">';
foreach ($attributeCodes as $attributeCode) {
$attrValue = $_product->getData($attributeCode['code']);
if(isset($attrValue)){
echo '<li><strong>'. $attributeCode['label'] .': </strong>'. $attrValue .'</li>';
} // if
} // foreach
echo '</ul>';
?>
Несколько вещей, чтобы заставить это работать:
Для любого атрибута, который вы хотите отобразить на страницах продукта, необходимо, чтобы для параметра "Видимый на странице просмотра продукта на интерфейсе" было установлено значение "Да", иначе они не будут включены в запрос для ОБЪЕДИНЕНИЯ всех атрибутов продукта вместе, и вы не сможете получить доступ к $_product
без перезагрузки продукта.
Вы захотите получить метку атрибута по хранилищу из модели атрибутов, изменив это
/* @var $child Mage_Eav_Model_Entity_Attribute */
$attributeCodes[] = $attribute->getAttributeCode();
К этому:
$storeId = Mage::app()->getStore()->getId();
//....//
/* @var $child Mage_Eav_Model_Entity_Attribute */
$attributeCodes[ $attribute->getAttributeCode() ] = $attribute->getStoreLabel($storeId);
При этом укажите, что вы должны знать метку для каждого атрибута, и у вас будет код атрибута в качестве ключа массива, который затем будет передан getAttributeText()