最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - nested categories dropdown in magento - Stack Overflow

programmeradmin4浏览0评论

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:

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

or this layout would be better:

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!

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:

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

or this layout would be better:

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!

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Apr 19, 2014 at 9:33 s_hs_h 1,4962 gold badges27 silver badges63 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5 +50

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>
$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 '';
}

}
$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();
}

}
发布评论

评论列表(0)

  1. 暂无评论