taral lokhande
taral lokhande

Reputation: 19

How to display selected products based on Customer Group in Magento

I want to create group of customers in Magento for eg. Group 1, Group 2. Now Suppose we have 10 products in out catalog, I want to assign only certain products to a particular group of customers. Now when a Customer say from Group 1 logs in, he should be able to see only those products that are assinged to Group 1 and not all products.

Upvotes: 1

Views: 1930

Answers (1)

Radoslav Stoyanov
Radoslav Stoyanov

Reputation: 1710

You can make a product attribute of type multiselect with options corresponding to the available customer groups. Then for each product select the groups that it will be available to. After that you can override Mage_Catalog_Model_Category::getProductCollection and check if customer is logged in, and if so, check his customer group. After that you can filter the product collection by this customer group. Your code should be something like this:

class Namespace_Module_Model_Rewrite_Catalog_Category extends Mage_Catalog_Model_Category {
    public function getProductCollection()
    {   
        if(Mage::getSingleton('customer/session')->isLoggedIn()){
            // Get group id
            $group_id = Mage::getSingleton('customer/session')->getCustomerGroupId();
            // Get customer group code
            $group = Mage::getModel('customer/group')->load($group_id);
            $group_code = $group->getCode();

            // Get multiselect attribute options
            $attributeOptionArray = array();
            $attrribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'customer_group_attribute_code');
            foreach ($attrribute->getSource()->getAllOptions(true, true) as $option) {
                $attributeOptionArray[$option['value']] = $option['label'];
            }

            $collection = Mage::getResourceModel('catalog/product_collection')
                    ->setStoreId($this->getStoreId())
                    ->addAttributeToFilter('customer_group_attribute_code', array('finset' => array_search($group_code, $attributeOptionArray)));
        } else {
            $collection = Mage::getResourceModel('catalog/product_collection')
                ->setStoreId($this->getStoreId())
                ->addCategoryFilter($this);
        }

        return $collection;
    }
}

Upvotes: 2

Related Questions