2

我需要在 Magento 1.7 上创建一个分组产品页面

为此,我添加了一个产品作为分组产品,并在那里关联了一些简单的产品。分组的产品在前端以表格行的形式一一显示。我的要求是在相关产品的相应类别中显示此页面。

例如:- 我有两个类别餐桌餐椅

我创建了一个分组产品,比如Lyn Dining set,并关联了两个简单的产品lyn Dining table(来自Dining Tables类别)和Lyn Dining Chair(来自Dining Chair类别)。默认情况下,它将在表格行中一一显示。像这样:-

Lyn Dining Table    Product Attributes...
Lyn Dining Chair    Product Attributes...
......................................
......................................
......................................

但我需要在相应的类别标题中显示。那是:-

Dining Table:-
Lyn Dining Table    Product Attributes...
......................................
......................................

Dining Chair:-
Lyn Dining Chair    Product Attributes...
......................................
......................................

为此,我编辑了 grouped.phtml 文件。首先,我用这段代码获取了类别名称:-

        /**
         * get categories from a product
         */
        $categoryIds = $this->htmlEscape($_item->getCategoryIds());

        /**
         * looping through the array of category ids
         */
        foreach($categoryIds as $categoryId) {
            $category = Mage::getModel('catalog/category')->load($categoryId);
            $categoryB=$category->getName();
            }

通过这个我可以获取类别名称。但我不知道如何实现循环,以便所有产品都可以列在相应的类别中。请任何人伸出援手。

4

1 回答 1

0

我会创建一个辅助函数,像这样(请记住,这段代码还是有点粗糙):

公共函数 formatProductsWithCategories($products) { $categories = array(); $categoryProducts = 数组();$hasOrphans = 假;

    foreach ($products as $product) {
        $categories = array_merge($product->getCategoryIds(), $categories);
        foreach($product->getCategoryIds() as $categoryId) {
            $categoryProducts[$categoryId][] = $product;
            $found = true;
        }

        if (!$found){
            $categoryProducts["empty"][] = $product;
            $hasOrphans = true;
        }
    }

    $categoryCollection = Mage::getResourceModel('catalog/category_collection')
        ->addAttributeToFilter('entity_id', array('in', $categories))
        ->addAttributeToSelect('name');

    $categoryCollection->load();

    if ($hasOrphans) {
        $categoryCollection->addItem(
            Mage::getModel('catalog/category')
                ->addData(array(
                    'id' => 'empty',
                    'name' => 'No Categories'
            ))
        ); // assigning orphan values
    }

    foreach ($categoryCollection as $category) {
        if (array_key_exists($category->getId(), $categoryProducts)) {
            $category->setProducts($categoryProducts[$category->getId()]);
        }
    }

    return $categoryCollection;
}

然后,在您的 grouped.phtml 模板中,执行以下操作:

<?php $categories = Mage::helper('helper_module/category')->formatProductsWithCategories($_associatedProducts); ?>
<?php foreach ($categories as $category):?>
    <tr><td><?php echo $category->getName();?></td></tr>
    <?php foreach ($category->getProducts() as $_item): ?>
         // . . .  Existing loop here . . .
    <?php endforeach; ?>
<?php endforeach; ?>
于 2012-11-16T18:07:16.877 回答