Monday, July 30, 2012

Magento:: Get Upsell products collection using Product Id

   // Get product object.
   $object = Mage::getModel('catalog/product');
   //Get product detail using product id  (Suppose you have product id is : $product_id)
   $_product = $object->load($product_id);
   // Fetch list of upsell product using query.
   $upsell_product = $_product->getUpSellProductCollection()->addAttributeToSort('position', Varien_Db_Select::SQL_ASC)->addStoreFilter();

   //check if record is empty or not
   $count = count($upsell_product);
   if(empty($count)) :
       //if empty
       echo "Record not found";


     //if result is not empty then get  upsell product detail using foreach loop
      foreach($upsell_product as $_upsell):
         //get detail of single upsell prdocut using upsell product id
         $upsp = $object->load($_upsell->getId());

         echo "Product Name : ". $upsp->getName();
         echo "Poduct url : ". $upsp->getProductUrl();
         echo "Product regular price : ". $upsp->getPrice();


Friday, July 27, 2012

Create Simple popup in HTML, JavaScript

>> Simple Pop up HTML, JavaScript ::

    <style type="text/css">
        display: none;
        position: fixed;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 100%;
        background-color: #000000;
        -moz-opacity: 0.8;
        filter: alpha(opacity=80);
        background-color: #FFFFFF;
        height: 21px;
        position: absolute;
        right: 0;
        text-decoration: none;
        top: -21px;
        width: 50px;
    #popBox{ width:591px; position:fixed; height:auto; background:#FFF; display:none; z-index:50000; top:20%; left:30%; }
    <div id="popX" class="black_overlay"></div>
    <div id="popBox"> <a class="pop_me" onClick="document.getElementById('popX').style.display='none'; document.getElementById('popBox').style.display='none';" href="javascript:;">Close [x]</a>
      <div class="pop_alert"> Your content here.... </div>
    <button onClick="document.getElementById('popX').style.display='block'; document.getElementById('popBox').style.display='block';">Open Popup</button>

Friday, July 20, 2012

Magento:: Add attribute option programmatically

$installer = new Mage_Eav_Model_Entity_Setup('core_setup');

$ProductEntityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$Option = array();
$Option['attribute_id'] = $installer->getAttributeId($ProductEntityTypeId, 'attribute_id');
$Option['value']['option'][0] = "value";

Get time difference in php

>>  To get time difference between two time.

     function getMyTimeDiff($t1,$t2)
        $a1 = explode(":",$t1);
        $a2 = explode(":",$t2);
        $time1 = (($a1[0]*60*60)+($a1[1]*60)+($a1[2]));
        $time2 = (($a2[0]*60*60)+($a2[1]*60)+($a2[2]));
        $diff = abs($time1-$time2);
        $hours = floor($diff/(60*60));
        $mins = floor(($diff-($hours*60*60))/(60));
        $secs = floor(($diff-(($hours*60*60)+($mins*60))));
        $result = $hours.":".$mins.":".$secs;
        if($hours == 0){
            return $mins.":".$secs;
            return false;

>> To get the date difference from current datetime with day, hours, min & second.
It'll return the time difference if the difference is <=10

        function dateTimeDiff($data_ref){
             // Get the current date
             $current_date = date('Y-m-d H:i:s');
             // Extract from $current_date
             $current_year = substr($current_date,0,4);
             $current_month = substr($current_date,5,2);
             $current_day = substr($current_date,8,2);
             // Extract from $data_ref
             $ref_year = substr($data_ref,0,4);
             $ref_month = substr($data_ref,5,2);
             $ref_day = substr($data_ref,8,2);
             // create a string yyyymmdd 20071021
             $tempMaxDate = $current_year . $current_month . $current_day;
             $tempDataRef = $ref_year . $ref_month . $ref_day;
             $tempDifference = $tempMaxDate-$tempDataRef;
             // If the difference is GT 10 days show the date
             if($tempDifference >= 10){
                 echo $data_ref;
             } else {
                 // Extract $current_date H:m:ss
                 $current_hour = substr($current_date,11,2);
                 $current_min = substr($current_date,14,2);
                 $current_seconds = substr($current_date,17,2);
                 // Extract $data_ref Date H:m:ss
                 $ref_hour = substr($data_ref,11,2);
                 $ref_min = substr($data_ref,14,2);
                 $ref_seconds = substr($data_ref,17,2);
                 $hDf = $current_hour-$ref_hour;
                 $mDf = $current_min-$ref_min;
                 $sDf = $current_seconds-$ref_seconds;
                 // Show time difference ex: 2 min 54 sec.
                             $mDf = 60 + $mDf;
                             $hDf = $hDf - 1;
                             echo $mDf . ' min';
                         } else {
                            echo $hDf. ' hr ' . $mDf . ' min';
                     } else {
                            echo $mDf . ' min ' . $sDf . ' sec';
                         } else {
                            echo $sDf . ' sec';
                 } else {
                    echo $dDf . ' days';

Magento:: Admin form Field

You'll surely get many forum of admin field in magento form. So, I'm showing you in a different way. You need to write this code in your module app/code/(local/community)/Companyname/Modulename/Block/Adminhtml/Modulename/Edit/Tab/Form.php
Find the method _prepareForm() and add which field you want to add.

How to add Text Field :

>> $fieldset->addField('fieldName', 'text', array(
          'label'     => Mage::helper('form')->__('Banner Name'),
          'class'     => 'required-entry',
          'required'  => true,        // true,false
          'name'      => 'name',
          'onclick' => "alert('add javascript if neeed');",
          'onchange' => "alert('add javascript if neeed');",
          'style'   => "width:15px",
          'value'  => 'Default value',
          'disabled' => false,        // true,false
          'readonly' => true,        // true,false
          'after_element_html' => '<small>Add any html or javascript</small>',

You can also add field attribute(e.g. label, class, name) like this way.

>>    $textFiled = $fieldset->addField('fieldName', 'text');
       $textFiled->setLabel(Mage::helper('form')->__('Banner Name'));
            function customFunction(element){
Same thing will applicable for Max types of form field with a small changes.

Time >> $fieldset->addField('fieldName', 'time');

TextArea >> $fieldset->addField('fieldName', 'textarea');

Date >> $fieldset->addField('fieldName', 'date', array(
          'label'     => Mage::helper('form')->__('Date'),
          'image' => $this->getSkinUrl('images/grid-cal.gif'),
          'format' => Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT)
Submit Button >> $fieldset->addField('submit', 'submit');

DropDown >> $fieldset->addField('fieldName', 'select', array(
          'label'  => Mage::helper('form')->__('Select'),
          'values' => array('0'=>'Please Select','1' => 'Option1','2' => 'Option2', '3' => 'Option3'),

Drop down with optiongroup
>> $fieldset->addField('fieldName', 'select', array(
          'label'  => Mage::helper('form')->__('Select Value'),
          'values' => array(
                                '0'=>'Please Select',
                                '1' => array(
                                    'value'=> array(array('value'=>'2' , 'label' => 'Option2') , array('value'=>'3' , 'label' =>'Option3') ),
                                    'label' => 'Length'
                                '2' => array(
                                    'value'=> array(array('value'=>'4' , 'label' => 'Option4') , array('value'=>'5' , 'label' =>'Option5') ),
                                    'label' => 'Type'

Radio Button >> $fieldset->addField('fieldName', 'radio');

Multi Radio Button >> $fieldset->addField('fieldName', 'radios', array(
          'values' => array(

Password Field >> $fieldset->addField('fieldName', 'password');

Note >> $fieldset->addField('fieldName', 'note');

Multiselect >> $fieldset->addField('fieldName', 'multiselect', array(
          'values' => array(
                            '0'=> array( 'label' => 'Please Select', 'value' => '0'),
                            '1' => array(
                                'value'=> array(array('value'=>'2' , 'label' => 'Option2') , array('value'=>'3' , 'label' =>'Option3') ),
                                'label' => 'Length'
                            '2' => array(
                                'value'=> array(array('value'=>'4' , 'label' => 'Option4') , array('value'=>'5' , 'label' =>'Option5') ),
                                'label' => 'Type'

Multiline >> $fieldset->addField('fieldName', 'multiline');

Link >> $fieldset->addField('fieldName', 'link', array('href' => ''));

Label >> $fieldset->addField('fieldName', 'label');

Image Upload >> $fieldset->addField('fieldName', 'image');

File Upload >> $fieldset->addField('fieldName', 'file');

Checkbox >> $fieldset->addField('fieldName', 'checkbox');

Multi Checkbox >> $fieldset->addField('fieldName', 'checkboxes', array(
          'label'     => Mage::helper('form')->__('Checkboxs'),
          'name'      => 'Checkbox',
          'values' => array(

Magento:: Session and Cookie handling

Magento provides very easy way to handle Cookie and session.
Magento session:
    >> Magento session is handle by core Module 'core/session'. Here is the way to save Session in magento

            $session = Mage::getSingleton("core/session");

            $session->setData("username", "value");     //This will store a session variable name "username"
            To get This session value we can use one of these following ---
    >> And session can be removed with setting session variable null
            $session->setData("username", null);

Cookie Handling in Magento:
    >> Setting cookie
            Mage::app()->getCookie()->set('cookie_name', "cookie_value", $lifetime,$domain,$httponly);
    >> Getting cookie in magento

Customer Login By Id in Magento

    >> $email = "";
          $customer = Mage::getModel('customer/customer');

Wednesday, July 18, 2012

Magento:: Set products per column, page in category listing

>> Go to Admin=>Manage categories=> Then click on the custom design tab
      If you want to display 20 products per page, with 5 columns. Then you have 5 products on each row.

<reference name="product_list">
     <action method="setColumnCount"><columns>5</columns></action>

<reference name="product_list_toolbar">
     <!-- Your default products count : 10 -->
     <action method="addPagerLimit"><mode>grid</mode><limit>10</limit></action>        
      <!-- Your new products count : 20 -->
     <action method="addPagerLimit"><mode>grid</mode><limit>20</limit></action>        
      <!-- The total number of products to display per page -->
     <action method="setDefaultGridPerPage"><limit>20</limit></action>

Magento: Display Products On Home Page

New Products
       >> To Display New product on home page add this block to your CMS home page in content section..

{{block type="catalog/product_new" name="" alias="product_homepage" template="catalog/product/new.phtml"}}

       >>   Now Set the date to these attributes:
                             >>    Set Product as New from Date and
                             >>    Set Product as New to Date


      >> Place this code to this path:- app/code/core/Mage/Cataloge/Model/Product.php

    public function isNew($date=null)
        if($date==null) {
            $date = $this->getResource()->formatDate(time());
        if(!$this->getData('news_from_date')) {
            return false;
        $current_date = new DateTime($date); // compare date
        $from_date = new DateTime($this->getData('news_from_date')); // begin date
        $to_date = new DateTime($this->getData('news_to_date')); // end date
        $return = ($current_date >= $from_date && $current_date <= $to_date);
        return $return;

   >> Next add this code into your phtml page where you want to show this product:-

    <div class="new">
      <?php if ($_product->isNew() == true): ?>


      <?php endif; ?>

All Products
    >>  Add this block to your CMS home page in content section..
{{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" template="catalog/product/list.phtml"}}

Display Products of a category
    >>  Add this block to your CMS home page in content section..
 {{block type="catalog/product_list" name="home.catalog.product.list" alias="products_homepage" category_id="4" template="catalog/product/list.phtml"}}

Monday, July 16, 2012

Magento:: CMS page collections, identifier

   >>   Mage::helper('cms/page')->getPage()->getIdentifier(); 

    /*  It will show CMS page Identifier e.g. home, about-us
   >> cms page :
         $store = Mage::app()->getStore();
         $cms_pages = Mage::getModel('cms/page')->getCollection();
         $pageTitle = array();
         $pageUrl2 = array();
         foreach($cms_pages as $_page)
             $data = $_page->getData();
             echo $pageUrl2[] = $data['identifier'];
             echo "<br />";
             echo $pageTitle[] = $data['title'];
             echo "<br />";

   >>   <?php $block = Mage::getModel('cms/block')->load('Your Block Name');

         // Gets Title of your Block
         echo $block->getTitle();
         // Gets Content of your Block
         echo $block->getContent(); ?>

   >> Get page title :

                         ***********         Good Luck        **********

Magento:: current url, category, product

   >>   mage::helper('core/url')->getCurrentUrl(); 

         //  It will show the current url     

   >>   mage::helper('core/url')->getHomeUrl();   

        //  It will show the home url    

   >> Current category ::
         $cat = Mage::registry('current_category');
         echo $cat->getName();

  >> Current Product ::
         $_product = Mage::registry('current_product');

                     ***********         Good Luck        **********

Magento::get url path for skin, media, js

 >>   Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);

   >>   Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);

   >>   Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

   >>   Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);

   >>    Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

        ***********         Good Luck        **********

Remove item from cart By ID in Magento

<?php echo $this->getUrl('checkout/cart/delete', array('id' => 'item_id')); ?>

Magento:: Shopping Cart grand total, subtotal, Discount

$quote = Mage::getSingleton('checkout/cart')->getQuote();

$grandTotal = $quote->getGrandTotal();

$subTotal =  $quote->getSubtotal();


$totals =  $quote->getTotals();

$subtotal = $totals["subtotal"]->getValue();

$Discount = $totals["discount"]->getValue();

Add Simple product to cart by url in Magento

echo Mage::getUrl('checkout/cart/add', array('product'=>$_item->getId(),'qty'=>1))

Magento :: Total Quantity in Shopping Cart

      mage::helper('checkout/cart')->getSummaryCount();   // show total quantity
      mage::helper('checkout/cart')->getCart()->getItemsCount();   // show total

Random Products in Magento

-: To view random product in your home page :- 
   >> First you have add this code to your CMS home page content..

    {{block type="catalog/product_list_random" name="product_random" template="catalog/product/rand_prod.phtml"}}

   >> create 'rand_prod.phtml' in this directory ...


   >> Mage::getSingleton('catalog/layer')->setData("product_collection",NULL);
      $this->_productCollection = null;
      $_collectionSize = $_productCollection->count() ;
      $_items = $_productCollection->getItems(); 
       // shuffle($_items); 

      foreach ($_items as $_product)
        echo $_product->getName();
        echo Mage::getModel('catalog/product')->load($_product->getId())->getDescription();
        /* 2nd echo will print product description after getting load  */

   >> Or you can do it By one line
$productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));

      follow this url I wish you will get help.... It's very simple

            ********       Good Luck       ************

How to Show Featured Products in Magento

Here I'll show you how to add featured products in Magento. "Featured" is a term that normally we use. You can use another name but here I'm showing you with the name "Featured". You can show this featured product collections in Home Page or any other page. In two way we can achieve this. First we can create an attribute in product level and get collection with filter of that attribute. Another one the easy way, we can create a category named "Featured" and assign those products you want to show in your phtml page.

Here is the First Step:

>>    Create new "Featured" attribute
        Create a new attribute by going to Catalog -> Attributes -> Manage Attributes -> Add New Attribute.
        Attribute Properties
            Attribute Identifier: featured
            Catalog Input Type for Store Owner: Yes/No
            Unique Value (not shared with other products): No
            Values Required: No
            Input Validation for Store Owner: None
            Apply To Configurable/Grouped Product: Yes
        Front End Properties
            Use in quick search: No
            Use in advanced search: Yes
            Comparable on Front-end: No
            Use In Layered Navigation (Can be used only with catalog input type 'Dropdown'): No
        System Properties
            Data Type for Saving in Database: String
            Globally Editable: No
            Visible on Catalog Pages on Front-end: Yes
        Manage Label/Options
            Default: Featured Product
            English: Featured Product

Now set the attribute within ant attribute set by going to Catalog -> Attributes -> Manage Attribute Set.
you're ready with the attribute now set the attribute value "Yes" by editing those products you want to show in your phtml page.
>>  Add this code in your phtml page:

    $featured_products = Mage::getModel('catalog/product')
                                    ->addAttributeToFilter('status', 1)
                                    ->addAttributeToFilter('visibility', 4)
                                    ->addAttributeToFilter('featured', 1);
    foreach($featured_products as $_product)
        echo $_product->getName();

Above is the example of showing by attribute. Now I'm Showing you the Second Step with category. It's the simple way. Create a category named "Featured" and make the category attribute "Include in Navigation Menu" false. In this category add some products which you want to show in your phtml page.

>> Add this code in your phtml page:

$category = Mage::getModel('catalog/category')->load(15);  // Here 15 is your new category ID
        $collection = $category->getProductCollection();