Magento – How to resolve the Error “Call to a member function getChildren() on null”

layered-navigationsidebarsubmenu

I wish to display the level1 and level2 subcategories of current active category in layered navigation in list page. So I gave the below code in catalog/category/view.phtml :

 <div class="sidebar-block">
<?php
$html = '';

$children = $menuTree->getChildren();
$parentLevel = $menuTree->getLevel();
$childLevel = is_null($parentLevel) ? 0 : $parentLevel + 1;

$counter = 1;
$childrenCount = $children->count();
$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
        ->addAttributeToSelect(array('name', 'thumbnail'))
        ->addAttributeToFilter('is_active', 1)
        ->addIdFilter($category->getChildren())
 ?>
    <div class="block-content clearfix">
        <ul class="subcategories">
            <?php foreach ($categories as $category): ?>
        <?php


foreach ($children as $child) {
    $child->setLevel($childLevel);
    $child->setIsFirst($counter == 1);
    $child->setIsLast($counter == $childrenCount);
    $child->setPositionClass($itemPositionClassPrefix . $counter);

    $outermostClassCode = 'level'. $childLevel;
    $_hasChildren = ($child->hasChildren()) ? 'has-children' : '';

    $html .= '<li '. $this->_getRenderedMenuItemAttributes($child) .'>';

    $html .= '<a href="'. $child->getUrl() .'" class="'. $outermostClassCode .' '. $_hasChildren .'">'. $this->escapeHtml($this->__($child->getName())) .'</a>';

    if (!empty($childrenWrapClass)) {
        $html .= '<div class="'. $childrenWrapClass .'">';
    }

    $nextChildLevel = $childLevel + 1;

    if (!empty($_hasChildren)) {
        $html .= '<ul class="level'. $childLevel .'">';
        $html .=     $this->render($child, $childrenWrapClass);
        $html .= '</ul>';
    }

    if (!empty($childrenWrapClass)) {
        $html .= '</div>';
    }

    $html .= '</li>';

    $counter++;
} ?>
            <?php endforeach; ?>
        </ul>
    </div>
</div>

am getting the error like Call to a member function getChildren() on null
How to resolve this? What should be done.Or is this approach wrong? Help please. am stuck.

Best Answer

If error says that you call function on null, first thing I would do is to check variable $category or $menuTree with print_r() or var_dump - maybe they are in fact null, which means the objects which should be under these varaibles or you think they should be, in fact are not assigned to them. Later if you detect which and if varaible is empty you should figure out way and then you can perform some changes in your code to get what you've planned.

Related Topic