nested categories dropdown in magento

2020-07-27 16:15发布

I have the following working code in magento frontend in a form for customer "add a product" functionality that Im developing:

Helper area:

public function getCategoriesDropdown() {

    $categoriesArray = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))
        ->load()
        ->toArray();


    foreach ($categoriesArray as $categoryId => $category) {
        if (isset($category['name'])) {
            $categories[] = array(
                'label' => $category['name'],
                'level'  =>$category['level'],
                'value' => $categoryId
            );
        }
    }
    return $categories;
}

PHTML File:

<select id="category-changer" name="category-changer" style="width:150px;">
        <option value="">--Select Categories--</option>
            <?php
             $_CategoryHelper = Mage::helper("marketplace")->getCategoriesDropdown();
                        foreach($_CategoryHelper as $value){
                            foreach($value as $key => $val){

                                if($key=='label'){
                                    $catNameIs = $val;
                                }
                                if($key=='value'){
                                    $catIdIs = $val;
                                }
                                if($key=='level'){
                                    $catLevelIs = $val;
                                    $b ='';
                                    for($i=1;$i<$catLevelIs;$i++){
                                        $b = $b."-";
                                    }
                                }
                            }
                            ?>
              <option value="<?php echo $catIdIs; ?>"><?php echo $b.$catNameIs ?></option>
                        <?php
                        }
                        ?>
                    </select>

this code generates a dropdown with categories and subcategories. like this one: enter image description here

my main idea is to create n level nested chained dropdowns for subcategories like this example: enter image description here

or this layout would be better: enter image description here

any guidance or code example to modify the proposed php in order to include an ajax call, or javascript to generate those frontend chained frontends will be appreciated

brgds!

3条回答
贼婆χ
2楼-- · 2020-07-27 16:34
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();

$categoriesHierachy = getChildrenCategoryOptions($rootCategoryId);


function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();

if( $_categoryCollection->count() > 0 ) {
    foreach($_categoryCollection as $_category) {
        $array[$_category->getLevel()][$_category->getId()]['name'] = $_category->getName();
        $array[$_category->getLevel()][$_category->getId()]['subcategories'] = getChildrenCategoryOptions($_category->getId());
    }
    return $array;
}
else {
    return array();
}

}
查看更多
ら.Afraid
3楼-- · 2020-07-27 16:35

Here is my way:

In helper class, add method:

public function getCategoriesDropdown() {
    $categories = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'));

    $first = array();
    $children = array();
    foreach ($categories->getItems() as $cat) {
        if ($cat->getLevel() == 2) {
            $first[$cat->getId()] = $cat;
        } else if ($cat->getParentId()) {
            $children[$cat->getParentId()][] = $cat->getData();
        }
    }

    return array('first' => $first, 'children' => $children);
}

In PHTML File:

<?php $tree = $this->helper('xxx')->getCategoriesDropdown(); ?>
<script type="text/javascript">
    var children = $H(<?php echo json_encode($tree['children']) ?>);

    function showCat(obj, level) {
        var catId = obj.value;
        level += 1;
        if ($('cat_container_' + level)) {
            $('cat_container_' + level).remove();
        }
        if (children.get(catId)) {
            var options = children.get(catId);
            var html = '<select id="cat_' + catId + '" onchange="showCat(this, ' + level + ')">';
            for (var i = 0; i < options.length; i++) {
                html += '<option value="' + options[i].entity_id + '">' + options[i].name + '</option>';
            }
            html += '</select>';
            html = '<div id="cat_container_' + level + '">' + html + '</div>';

            $('sub_cat').insert(html);
        }
    }
</script>
<select id="first_cat" onchange="showCat(this, 2)">
    <?php foreach ($tree['first'] as $cat): ?>
        <option value="<?php echo $cat->getId() ?>"><?php echo $cat->getName() ?></option>
    <?php endforeach ?>
</select>
<div id="sub_cat"></div>
查看更多
欢心
4楼-- · 2020-07-27 16:48
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();

/* You can play with this code */
echo '<select>';
echo getChildrenCategoryOptions($rootCategoryId);
echo '</select>';
/* You can play with this code */

function getChildrenCategoryOptions($categoryId) {
$html = '';
$_categoryCollection = Mage::getModel('catalog/category')->load($categoryId)->getChildrenCategories();

if( $_categoryCollection->count() > 0 ) {
    foreach($_categoryCollection as $_category) {

        $html .= '<option value="'.$_category->getId().'">'.str_repeat("-", ($_category->getLevel() - 2)).$_category->getName().'</option>';
        $html .= getChildrenCategoryOptions($_category->getId());
    }
    return $html;
}
else {
    return '';
}

}
查看更多
登录 后发表回答