Monday, July 30, 2012

Magento:: Get Upsell products collection using Product Id


<?php
  
   // 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";

   else:

     //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();
        
       endforeach;
  
   endif;

?>

Friday, July 27, 2012

Create Simple popup in HTML, JavaScript


>> Simple Pop up HTML, JavaScript ::

    <style type="text/css">
    .black_overlay{
        display: none;
        position: fixed;
        top: 0%;
        left: 0%;
        width: 100%;
        height: 100%;
        background-color: #000000;
        text-align:center;
        z-index:5000;
        -moz-opacity: 0.8;
        opacity:.80;
        filter: alpha(opacity=80);
    }
    .pop_me{
        background-color: #FFFFFF;
        height: 21px;
        position: absolute;
        right: 0;
        text-decoration: none;
        top: -21px;
        width: 50px;
    }
    .pop_alert{
    min-height:200px;
    }
    #popBox{ width:591px; position:fixed; height:auto; background:#FFF; display:none; z-index:50000; top:20%; left:30%; }
    </style>
    <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>
    </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');
$installer->startSetup();

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


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;
        }else{
            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.
                 if($dDf<1){
                     if($hDf>0){
                         if($mDf<0){
                             $mDf = 60 + $mDf;
                             $hDf = $hDf - 1;
                             echo $mDf . ' min';
                         } else {
                            echo $hDf. ' hr ' . $mDf . ' min';
                         }
                     } else {
                         if($mDf>0){
                            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->setName("name");
       $textFiled->setLabel(Mage::helper('form')->__('Banner Name'));
    $textFiled->setAfterElementHtml('
        <script>
            function customFunction(element){
                alert(element.value);
            }
        </script>
    ');
    $textFiled->setOnclick("customFunction(this)");
   
 
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(
                        array('value'=>'1','label'=>'Radio1'),
                        array('value'=>'2','label'=>'Radio2'),
                        array('value'=>'3','label'=>'Radio3'),
                       ),
        ));

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' => 'https://www.facebook.com/onestepmagentosolutions'));

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(
                            array('value'=>'1','label'=>'Checkbox1'),
                            array('value'=>'2','label'=>'Checkbox2'),
                            array('value'=>'3','label'=>'Checkbox3'),
                       ),
        ));
       
       
       

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"
                            OR
            $session->setUsername("value");
           
            To get This session value we can use one of these following ---
           
            $session->getData("username");
                        OR
            $session->getUsername();
   
    >> And session can be removed with setting session variable null
   
            $session->setData("username", null);
            $session->setUsername("");
=========================================================

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



Customer Login By Id in Magento


    >> $email = "name@gmail.com";
          $customer = Mage::getModel('customer/customer');
          $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
          $customer->loadByEmail(trim($email));
          Mage::getSingleton('customer/session')->loginById($customer->getId());