4

I have 100 products in my store. 4 products (all in one category) are "special products" that cannot be purchased in the same cart with other 96 products. I would like to hide the "Add to Cart" button on the other 96 products if any of the 4 "special products" have been added to the cart.

The 4 "special products" CAN be purchased together, so I do not want to hide the "Add to Cart" button on those products. Only want the button hid on the other 96 products that are not compatible with the 4 "special products".

My template uses $_product->isSaleable, so I thought there would be a way to hide the button on the 96 products using that somehow. Being relatively new to Magento, I have not been able to figure out how to accomplish this. Might be the completely wrong way as well.

The 4 "special products" use a custom design, so my thought process was to simply remove $_product->isSaleable from that design template (the products are never out of stock and will always be available.)

A secondary option would be to block customers from adding one of the 96 products to the cart, and simply display a notice/message that informs them that they can't add to the cart because of the special product(s) already in the cart.

I am using Magento CE 1.8.1.

2
  • how do you set 4 special products as 'special' ? did you use an attribute for that? Commented Mar 20, 2014 at 1:27
  • Why don't you put those 4 sepcial products in a "special" category, save the id of that category in a Magento variable, and then check that if you have products in your carts, either all are of the special category or none are from the special category. I suggest you maybe hook on the checkout_cart_add_product_complete event to be able to remove that product when added. Commented Mar 20, 2014 at 9:55

2 Answers 2

0

If you are unable to save the products into a "special" category as @Julien suggested, you could set a different attribute set specifically for the products, or, if you can do neither of those, I would suggest setting a product attribute. Any way you do it, you'll still have to query the DB for these products, then grab your Cart and see if any items are in it.

So, let's create a product attribute, and call it "featured". Make a new attribute, as a Yes/No and assign it to the appropriate attribute set. Flag those 4 products as such.

Next, you need something along the lines of:

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(array('attribute'=>'featured','eq'=>'1'));

$exemptProducts = array();
$exemptProductFound = false;

foreach ($collection as $product) {
    $exemptProducts[] = $product->getId();
}

// now let's check if any are in the basket
$cart = new Mage_Checkout_Model_Cart();
$cart->init();

foreach ($cart->getItems() as $item) {
    if(in_array($item->getProductId(), $exemptProducts)) {
        // to make it simple, just set a flag
        $exemptProductFound = true;
    }
}

This could be in-line in your template, or in a function that you make available to your template (cleaner).

1

You can use an observer method to accomplish this. In order to use that, let us create a module that observes catalog_product_load_after event. This event will trigger whenever product view page is trying to load. Let our module name be Mysite_Disablebutton

Note : I assumes here you are using a custom product attribute with an identifier set_as_special_product to set a product as a special product. With that assumption, let us start

Your module's config file will look like this

Location : app/code/core/local/Mysite/Disablebutton/etc/config.xml

<config>
<modules>
    <Mysite_Disablebutton>
        <version>0.1.0</version>
    </Mysite_Disablebutton>
</modules>
<frontend>
    <events>
      <catalog_product_load_after>
          <observers>
              <disable_addtocart_btn>
                  <type>singleton</type>
                  <class>disablebutton/observer</class>
                  <method>disableAddtoCartButton</method>
              </disable_addtocart_btn>
          </observers>
      </catalog_product_load_after>
    </events>   
</frontend>
<global>
    <models>
        <disablebutton>
            <class>Mysite_Disablebutton_Model</class>
        </disablebutton>
    </models>
</global>
</config>

As you can see it has two section. One section defines the observer part and other section defines its model part. In model, you are going to define your observer.

Now let us make magento knows about our module.For this you need to add this file in the given location

Location:app/etc/modules/Mysite_Disablebutton.xml

<config>
<modules>
    <Mysite_Disablebutton>
        <active>true</active>
        <codePool>local</codePool>
    </Mysite_Disablebutton>
</modules>
</config>

Now its time to define our observer.Let us do that

Location : app/code/local/Mysite/Disablebutton/Model/Observer.php

<?php

class Mysite_Disablebutton_Model_Observer
{

    public function disableAddtoCartButton(Varien_Event_Observer $observer)
    {
            /*
            * get product that going to show in product view page
            */
            $currentPrdouct=$observer->getEvent()->getProduct();

            /*
            * declare a session variable
            * it will set to either true or false according to the cart condition
            * false -> if no special product in cart
            * true ->if special product does exist in cart
            */
            $session = Mage::getSingleton("core/session");
            $sessionVar="disableBtn".$currentPrdouct->getId();

            /*
            * defines general variables that we need to use in future
            */
            $yes="";$specialPdtIds=array();

            /*
            * loads special product attribute
            *this custom product attribute is used to set a product as special product
            * possible two values : yes or no
            * yes -> product is set as special product therogha admin
            * no -> product is not set as special product
            * here, get value of 'yes' option by loading this attribute, which we will use
                in future for checking
            */
            $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product','set_as_special_product');
            foreach($attribute->getSource()->getAllOptions(true,true) as $option)
            {
                if(strtolower(trim($option['label']))=="yes")
                {
                    $yes=$option['value'];
                    break;
                }
            }            

            if(!empty($currentPrdouct))
            {
                /*
                * this methos only works if your attribute idenifier is 'set_as_special_product'
                */
                $specialProductStatus=$currentPrdouct->getSetAsSpecialProduct();
                //if the current product is not a special product, it will go for checking cart
                if($specialProductStatus!=$yes)
                {
                    /*
                    *get cart prdoucts and check whether it is empty or not
                    */
                    $cart = Mage::getModel('checkout/cart')->getQuote();
                    $items=$cart->getAllItems();
                    if(!empty($items))
                    {
                        /*
                        * stores ids of cart product to an array
                        */
                        foreach ($items as $key=>$item) 
                        {
                            $specialPdtIds[$key]=$item->getProduct()->getId();

                        }
                        /*
                        *check whether any one of cart product is set as special product
                            * if varible empty -> means no special products
                            *if varible not empty -> has special product
                        */
                        $specialPdts=Mage::getModel('catalog/product')->getCollection()
                                        ->addAttributeToFilter('entity_id',$specialPdtIds )
                                        ->addAttributeToFilter('set_as_special_product',$yes);

                        if(!empty($specialPdts))
                        {
                            //special products exist; indicate it by sets session variable as true
                            $session->setData($sessionVar, true);
                        }
                        else
                        {
                            //no special product. Hence session variable sets to false
                            $session->setData($sessionVar, false);
                        }


                    }
                    //since cart is empty; sets session variable to false
                    else
                    {
                        $session->setData($sessionVar, false);
                    }
                }
                //current product is special prdouct; set session variable to false
                else
                {
                    $session->setData($sessionVar, false);
                }
            }
            else
            {
                $session->setData($sessionVar, false);
            }
    } 
}

I will explain what is our observer does in short : It will check whether our current product is special product or not. If not, it will check whether cart products exist or not. If exist, it will check whether cart contains any special product or not. If special product exist in cart, then it will set a session variable that indicates that, we need to disable(remove) add to cart button. If any one of the condition fails, it will set this session variable to false.

So we are so close. Now we need to check the status of our session variable in product view page, before displaying add to cart button. To do this go to

Location : app/design/frontend/<your_package>/<your_theme>/template/catalog/product/view.phtml

Replace following section

  <?php if($_product->isSaleable()): ?>
       <?php echo $this->getChildHtml('addtocart') ?>
       <?php if( $this->helper('wishlist')->isAllow() || $_compareUrl=$this->helper('catalog/product_compare')->getAddUrl($_product)): ?>
        <span class="or"><?php echo $this->__('OR') ?></span>
       <?php endif; ?>
  <?php endif; ?>

with this code

<?php
      /*look for button info*/
       $session = Mage::getSingleton("core/session");
       $sessionVar="disableBtn".$_product->getId();
       $btnStatus = $session->getData($sessionVar);
   if($btnStatus!==true):

?>
           <?php if($_product->isSaleable()): ?>
                <?php echo $this->getChildHtml('addtocart') ?>
                <?php if( $this->helper('wishlist')->isAllow() || $_compareUrl=$this->helper('catalog/product_compare')->getAddUrl($_product)): ?>
                     <span class="or"><?php echo $this->__('OR') ?></span>
                <?php endif; ?>
          <?php endif; ?>
      <?php endif; ?>

Thats it you are done. Good luck with your work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.