Categories
Magento 1

Retrieve a list of all parent category url keys in Magento

In this example, we only want to show a block for a product which resides within a particular category. We check all of the category’s parent categories and show the block if any of them match our $_allowedCategories array. Using URL keys instead of category IDs makes this code more portable between environments such as development and production where IDs may not be the same.

<?php
class Namespace_Module_Block_Catalog_Product_Request_Form extends Mage_Core_Block_Text_List
{
    protected $_allowedCateogies = array('shelters');

    protected function _toHtml()
    {
        $allCatUrls = array();

        // get an array of all parent category url keys
        if($product = Mage::registry('current_product')){
            $cats = $product->getCategoryCollection()->addAttributeToSelect('url_key');

            foreach($cats as $cat){
                $this->_getParentUrlKeys($cat, $allCatUrls);
            }
        }

        // Check whether the category is in the array
        foreach($this->_allowedCateogies as $category){
            if(in_array($category, $allCatUrls)){
                return parent::_toHtml();
            }
        }

        return '';
    }

    // Recursively get all of the parents url keys
    protected function _getParentUrlKeys(Mage_Catalog_Model_Category $cat, &$urlKeys)
    {
        if(!in_array($cat->getUrlKey(), $urlKeys)) {
            $urlKeys[] = $cat->getUrlKey();
        }

        if($cat->getParentCategory()->getId()){
            return $this->_getParentUrlKeys($cat->getParentCategory(), $urlKeys);
        }
    }
}

Categories
Magento 1

Setting Category & Product Attribute Defaults in Magento 1

When creating a new attribute, we can specify a default value to be saved alongside that attribute. However, these values do not propagate to categories or products which already exist. We can, however use load_after events to remedy this.

Confix XML

<global>
    <events>
        <catalog_category_load_after>
        	<observers>
        		<observer_name>
        			<type>singleton</type>
        			<class>module/observer</class>
        			<method>setDefaults</method>
        		</observer_name>
        	</observers>
        </catalog_category_load_after>
    </events>
</global>

Note: To set the default of a category use catalog_product_load_after instead

<?php
class Namespace_Module_Model_Observer
{
    public function setDefaults($observer)
    {
        $category = $observer->getCategory();

        if($category->getShowSizeRollover() === NULL){
            $category->setShowSizeRollover(true);
        }
    }
}

In this example we set the attribute ‘show_size_rollover’ to true if it’s not already been given a value. Because we’ve added this event in the global space, this value will propagate for both frontend and adminhtml.