Monday, 16 March 2015

Check if subcategory exists in current category in magento

Check if subcategory exists in current category


I have the following category setup in my magento store:
store root
|
bedroom    kitchen    
   bathroom    
   
|            |         
     |            
   
furniture  furniture  
   furniture         
   
lighting   lighting   
   misc
misc
     
   
I need to be able to check if the category misc exists as a subcategory in my current category or not, and if so show a particular block.
So if i was in the kitchen category it would not show but in bedroom and bathroom it would.
How can i do this this check?


You can get the list of subcategories of a category like this:
$currentCategoryId =
   10; 
   
$collection =
   Mage::getModel('catalog/category')->getCollection()
   
   ->addAttributeToFilter('is_active',
   1) //only active categories

      ->addAttributeToFilter('parent_id',
   $currentCategoryId);
If you want to check if only a specific category is present...in your case with the name 'misc' just add an additional filter to the code above:
$currentCategoryId =
   10; 
   
$collection =
   Mage::getModel('catalog/category')->getCollection()
   
   ->addAttributeToFilter('is_active',
   1) //only active categories
   
   ->addAttributeToFilter('parent_id',
   $currentCategoryId)
   
   ->addAttributeToFilter('name',
   'misc') //filter by name
    ->setPage(1,1)
   //set a limit to the collection

      ->addAttributeToSelect('url_key');
And you don't even need to load the full collection. You just need to check if the collection from above has at least 1 item in it.
if
   ($collection->getSize() == 1) {
    //
   'misc' exists
    $url
   = $collection->getFirstItem()->getUrl();
}
else {
    //
   no 'misc' subcategory for you.
}


No comments:

Post a Comment