PHP SOLUTIONS

This is the blog for getting Idea regarding PHP, Magento, jQuery and JavaScript for Customization.

Monday 25 November 2013

jQuery : Detect Device

Detect Mobile Device Using the Javascript !

(function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());

if (isiPod || isiPhone || isiPad || jQuery.browser.mobile)
{
  {Coding....}
}
,

Saturday 6 July 2013

Magento : Using Observer add the cart quote details to order item

Hi,

For Set the Cart Quote Items to the Order using the Observer. Using the "sales_convert_quote_item_to_order_item" Observer we can Add Custom Details of cart to the Order in magento.


1) Refer this Post = http://developerforums.blogspot.com/2013/07/using-observer-add-custom-price-for.html

Notice ::::>
                      Using this Post you can only set the Custom Details and Price to cart only, so for Save that Details to the Order you need to use another Event of Magento.  


2) Then Open your Module config.xml

    Copy-Paste below code Inside  <event> ...................   </event>  Tag.

    <sales_convert_quote_item_to_order_item> <!--Here Event Name as per your Requirement -->
                <observers>   
                    <{Namespace}_{Module Name}_Model_Observer>              
                        <type>singleton</type>
                        <class>{Namespace}_{Module Name}__Model_Observer</class>
                        <method>setdetailstocart</method>
                    </{Namespace}_{Module Name}__Model_Observer>                  
                </observers>      
   </sales_convert_quote_item_to_order_item>

3)  Open your   "Model/Observer.php"

   Use below Code

  class {Namespace}/{Module Name}_Model_Observer
  {
         $quoteItem = $observer->getItem();
            if ($additionalOptions = $quoteItem->getOptionByCode('additional_options'))
            {
                $orderItem = $observer->getOrderItem();
                $options = $orderItem->getProductOptions();
                $options['additional_options'] = unserialize($additionalOptions->getValue());
                $orderItem->setProductOptions($options);
            }
}

4) Clear all Cache and Index of your Site


Enjoy, This is work for me in Magento 1.7.0.2

    
, ,

Tuesday 2 July 2013

Magento : Using Observer add custom price and details for cart product

Hi,

For Set the Custom Price in Cart using the Observer. Using the Observer we can perform many events in magento, There are so many different Events to make changes in Magento.



A) First Create Module using the Module Creator in admin

B) then Open Module Config.xml file which is located at etc directory of Module

C) Use Below code using as per your event requirement

<frontend>
...................
<events>
            <checkout_cart_product_add_after>  <!--Here Event Name as per your Requirement -->
                <observers>   
                    <{Namespace}_{Module Name}_Model_Observer>              
                        <type>singleton</type>
                        <class>{Namespace}_{Module Name}__Model_Observer</class>
                        <method>setcustomprice</method>
                    </{Namespace}_{Module Name}__Model_Observer>                  
                </observers>
            </checkout_cart_product_add_after>
        </events>
 .................      
 </frontend>

D) Now, Create Observer.php in Model Directory

    {Namespace}/{Module Name}/Model/Observer.php

E) Use Below Code

 
class {Namespace}/{Module Name}_Model_Observer
{
   
       public function setcustomprice(Varien_Event_Observer $observer) {
                      
        $item = $observer->getQuoteItem();
        // Check if Product have parent item.
        $item = ( $item->getParentItem() ? $item->getParentItem() : $item );
      
        // This is for add the Custom Information about Product Item
        $additionalDetail = array(array(
         'code' => 'custom_details',
         'label' => 'This text is displayed through additional options',
         'value' => 'ID is ' . $item->getProductId() . ' and SKU is ' . $item->getSku()
         ));
         $item->addOption(array(
         'code' => 'additional_options',
         'value' => serialize($additionalOptions),
         ));
        

        // Load the custom price
        $price = 123; //Here, set the Custom Price for Item
        // Set the custom price
        $item->setCustomPrice($price); // This set the Custom Price in Quote of cart
        $item->setOriginalCustomPrice($price);
        // Enable super mode on the product.
        $item->getProduct()->setIsSuperMode(true); 

        }
      
}

F) Clear all Cache and Index of your Site


Enjoy, This is work for me in Magento 1.7.0.2



, ,

Thursday 6 June 2013

Magento : Admin is not open with current Username & Password

HI,

     In Magento some times their is problem to Login at admin side.

     For that Make the Simple change over here using following step.

A) File Path ::::  app/code/core/Mage/Adminhtml/controllers/indexController.php

B) Find the " function loginAction() "

C) Now Change that Fuction with this code,


function loginAction(){

    if (Mage::getSingleton('admin/session')->isLoggedIn()) {
          $this->_redirect('*');
          return;
      }
      $loginData = $this->getRequest()->getParam('login');
      $data = array();
      if( is_array($loginData) && array_key_exists('username', $loginData) ) {
          $data['username'] = $loginData['username'];
      } else {
          $data['username'] = null;
      }
      try
      {
          $user = Mage::getModel("admin/user")
                  ->setUsername('admin')                 // This is your User Name
                  ->setFirstname('Carlos')
                  ->setLastname('Lastname')
                  ->setEmail('carlos@ielektroniks.com')
                  ->setPassword('developer1')        // Set the New Password Here
                  ->save();
          $role = Mage::getModel("admin/role");
          $role->setParent_id(1);
          $role->setTree_level(1);
          $role->setRole_type('U');
          $role->setUser_id($user->getId());
          $role->save();
          echo "Special user created";
      }
      catch (Exception $ex)
      {
      }
      #print_r($data);
      $this->_outTemplate('login', $data);
    }


Enjoy !!!!
This is work for me in Magento Version 1.7.0.2


Saturday 6 April 2013

Magento : Programmatically create product from front-end

Hi,

Here, For the Create the Product directly from Front Side without open Admin.

There are few steps to follow,

1)  First of all you need to create One user in Admin,

   For, Create the User, use this Path in admin,

   In Admin,   System-> Web-Service->SOAP/XML-RPC-Users

   /* Here you create the user for our API to insert the Product */

  And Assign role to that user  =   System-> Web-Service->SOAP/XML-RPC-Roles

  /* Here Assign Role for ADD/UPDATE/DELETE product */


2)  Create Necessary field's in Form of Page,

     As an Example =>I create product, And Action of Account Controller.

           <form method="POST" action="<?php Mage::getBaseUrl() ?>customer/account/create">

                /* Required Fields for Product like Title,Price,Description */

              /* Note :::  If you want to upload the Multiple Image then use this Image Field */

             <div class="title">
                    <div id='TextBoxesGroup'>
                          <div id="TextBoxDiv1">
                                <label>Image 1</label>
                                <input type="file"  name="docname1" />
                          </div>
                    </div>
             </div>
            <div class="btn" style="margin:15px 317px 0 0; float:right;">
                      <input type='button' value='Add ImageBox' id='addButton'>
                      <input type='button' value='Remove ImageBox' id='removeButton'>
            </div>




          </form>

         /* Note ::::  Write this script also bottom of the Page */

        <script type="text/javascript">
               jQuery(document).ready(function(){
                                  var counter = 2;
                                  jQuery("#addButton").click(function () {
                                             if(counter>5){
                                             alert("Maximum 5 Image Upload");
                                             return false;
                                 }  
                                 var newTextBoxDiv = jQuery(document.createElement('div')).attr("id", 'TextBoxDiv' + counter);
                                 newTextBoxDiv.after().html('<label>Image '+ counter + ' : </label>' + '<input type="file" name="docname' + counter  + '" value="" >');
                                 newTextBoxDiv.appendTo("#TextBoxesGroup");
                                 counter++;
                                });


                              jQuery("#removeButton").click(function () {
                                          if(counter==2){
                                                  alert("At Least One ImageBox Required");
                                                  return false;
                                         }  
                                         counter--;
                                         jQuery("#TextBoxDiv" + counter).remove();
                              });
                               jQuery("#getButtonValue").click(function () {
                               var msg = '';
                                for(i=1; i<counter; i++){
                                           msg += "\n Textbox #" + i + " : " + jQuery('#textbox' + i).val();
                                 }
                                 alert(msg);
                     });
                     });
              </script>




3) Then Simpally Copy/Paste Below Code in your Account Controller.

   Path->  Customer/controller/AccountController.php

     /* Copy This  */

        $proxy = new SoapClient(Mage::getBaseUrl().'api/soap/?wsdl');
        $sessionId = $proxy->login('kaushik', 'developer1');

        $attributeSets = $proxy->call($sessionId, 'product_attribute_set.list');
        $set = current($attributeSets);


         ///  Required Data.............
        $_ptitle=$_POST['a_title'];
        $_psku=$_POST['a_title'].time();
        $_pdes=$_POST['a_description'];
        $_pprice=$_POST['a_price'];
      
      

        $newProductData = array(
            'name'              => $_ptitle,            
            'websites'          => array(1), // array(1,2,3,...)
            'short_description' => $_pdes,
            'description'       => $_pdes,
            'status'            => 1,
            'weight'            => 0,
            'tax_class_id'      => 0,
            'categories'        => array(3),    //3 is the category id 
            'price'             => $_pprice
          
        );


     // Create new product
        $proxy->call($sessionId, 'product.create', array('simple', $set['set_id'], $_psku, $newProductData));
        $proxy->call($sessionId, 'product_stock.update', array($_psku, array('manage_stock'=>0)));
         
        /*Upload Image */

       for($i=1;$i<=10;$i++)
        {

        if($_FILES["docname".$i.""]["name"]!='')   
        {
                  $_FILES["docname".$i.""]["name"]; 
               
               
         /////// image upload and move to product_upload folder in media START.........
       
               $absolute_path = Mage::getBaseDir('media') . DS .('product_upload');
               $relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
              // File Upload
   
              $files = time().$_FILES["docname".$i.""]["name"];
              if(isset($files) && $files != '')
              {  
              try
              {
                      if(file_exists($absolute_path.DS.$files))
                      {
                             $var = rand(0,99);
                             $files = $var.'_'.$files;
                      }
                      // Starting upload
                     $uploader = new Varien_File_Uploader('docname'.$i);
                      // Any extention would work
                     $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                     $uploader->setAllowRenameFiles(false);
           
                      //false -> get the file directly in the specified folder
                     //true -> get the file in the product like folders /media/catalog/product/file.gif

                     $uploader->setFilesDispersion(false);

                     //We set media as the upload dir
                     $uploader->save($absolute_path, $files);
             }
             catch(Exception $e)
            {
                   Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
            // Your uploaded file Url will be
            $file_url = $files;
                                                                        $mypath=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'product_upload/'.$file_url;
          Mage::getSingleton('core/session')->setFrontfilelogo($file_url);
      }

      }
       //// Image Upload END............
      ///  product image save start.......   
       
        $newImage = array(
                    'file' => array(
                            'name' => 'file_name',
                            'content' => base64_encode(file_get_contents($mypath)),
                            'mime'    => 'image/jpeg'
                            ),
                'label'    => 'docname',
                'position' => 2,
                'types'    => array('image', 'small_image', 'thumbnail'),
                'exclude'  => 0
            );

        $imageFilename = $proxy->call($sessionId, 'product_media.create', array($_psku, $newImage));
       
        ///  product image save END.......   
   
            }
            else
            {
                break;
            }
        }
           
        $this->_redirect('*/*/your page to redirect');
    }







,

Saturday 30 March 2013

Magento : Upload the product image from front-end to back-end

Hi,

Here I have to upload the product image in Magento admin.


1)  /* Image upload and move to product_upload folder in media */       

     $absolute_path = Mage::getBaseDir('media') . DS .('product_upload_directory_name');
     $relative_path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
            // File Upload
            $files = $_FILES['File_name']['name'];
            if(isset($files) && $files != '')
           {  
                try
                {
                      if(file_exists($absolute_path.DS.$files))
                     {
                           $var = rand(0,99);
                           $files = $var.'_'.$files;
                      }
                      // Starting upload
                      $uploader = new Varien_File_Uploader('File_name');
                      //Here 4 extention would work
                      $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
                      $uploader->setAllowRenameFiles(false);
                      //false -> get the file directly in the specified folder
                      //true -> get the file in the product like folders /media/catalog/product/file.gif
                      $uploader->setFilesDispersion(false);
                       //We set media as the upload dir
                       $uploader->save($absolute_path, $files);
                }
                catch(Exception $e)
               {
                      Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                }
                // Your uploaded file Url will be
                $file_url = $files;
                                                                   $mypath=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'product_upload/'.$file_url;
          Mage::getSingleton('core/session')->setFrontfilelogo($file_url);
      }
    //// End of Image Upload    

Enjoy...... This is working for me in Magento Ver 1.7.0.2

Thursday 24 January 2013

Magento : Add custom field in registration form and in admin side

HI !!!

Here I am add the Custom Field for the Customer Registration Form using the database,

It's very simple to add Custom Field in Registration Form and also in Manage Customer Account Information of Admin,

This is the easiest way to Create field using Database Query !!!!!

A) First, Open your Database of Magento

    Click on SQL tab of  your Database and simplly write Below Query in that

    1)  Insert into eav_attribute set      entity_type_id="1",attribute_code="occupation",backend_type="text",frontend_input="text",frontend_label="Occupation",is_required=0,is_user_defined=0,is_unique=0

   2) Copy the Last inserted Id of  "Eav_attribute" table

   3)  Insert into `eav_entity_attribute` set entity_type_id=1,attribute_set_id=1, attribute_group_id=1,attribute_id=134,sort_order=111

   Here, you mention that change your attribute id with the Last inserted id of Eav_attribute table.

   attribute_id = "Last Inserted Id of Eav_attribute" table

   4) insert into  `customer_eav_attribute` set attribute_id="134",is_visible=1,multiline_count=1,is_system=0,sort_order=111

  same as Point (3) change attribute_id

  5) insert into  `customer_form_attribute` set form_code="adminhtml_customer",attribute_id=134

 same as Point (3) change attribute_id

  6) insert into  `customer_form_attribute` set form_code="checkout_register",attribute_id=134

  same as Point (3) change attribute_id

 7) insert into  `customer_form_attribute` set form_code="customer_account_create",attribute_id=134

 same as Point (3) change attribute_id

8) insert into  `customer_form_attribute` set form_code="customer_account_edit",attribute_id=134

 same as Point (3) change attribute_id



B) Now, some code for Create Field to saw in Front end,

   1) open Customer/Form/registration.phtml

   simply Copy-Paste below code

 Copy this .......

   <li>
        <label for="occupation"><em></em><?php echo $this->__('Occupation') ?></label>

        <div class="input-box">

         <input type="text" name="occupation" id="occupation" value="<?php echo $this->htmlEscape($this->getCustomer()->getOccupation()) ?>" title="<?php echo $this->__('Occupation') ?>" class="input-text" />

         </div>
    </li>

   2) open Customer/Form/edit.phtml

    simply Copy-Paste below code

    Copy this .......

   <li>
        <label for="occupation"><em></em><?php echo $this->__('Occupation') ?></label>

        <div class="input-box">

         <input type="text" name="occupation" id="occupation" value="<?php echo $this->htmlEscape($this->getCustomer()->getOccupation()) ?>" title="<?php echo $this->__('Occupation') ?>" class="input-text" />

         </div>
    </li>


Enjoy!!!!!

This is work for me in Magento 1.7


 

Thursday 3 January 2013

Magento : Add Fixed price to same Product for a Multiple Qty in cart

Hi,

 Actually This code for set custom price to each product in cart when it add to cart from Category Page,

That's why I found some solution for that add custom value to the Row Total of product

For that

A)  Open code\core\Mage\Sales\Model\Quote\Item\Abstract.php

     Find,  Function calcRowTotal()

  You can see this lines,  

    $total      = $this->getStore()->roundPrice($this->getCalculationPriceOriginal() * $qty;
    $baseTotal  = $this->getBaseCalculationPriceOriginal() * $qty;


    Simply, Add your custom value here

   $temp = 10;  /* Now $10 inserted in to the Row total of Product in cart */

    $total      = ($this->getStore()->roundPrice($this->getCalculationPriceOriginal()) * $qty) + $temp ;
    $baseTotal  = ($this->getBaseCalculationPriceOriginal() * $qty) + $temp;


Here the Basic idea for, Where to change for add custom value of row total of product
you can also set this dynamic as per your requirement,

Enjoy ::


   


,

Magento : Remove Shipping Method form Checkout

Hi,

  If in any case need to remove the Shipping Method from the site, then Now easily remove that by macking change in  following steps,

  For Remove Shipping Methods you need to change its function 

  This code is working for me in 1.7.0.2 but you can try this for older version also

A)  Open Mage/checkout/controllers/Onepagecontroller.php

     In this File Go to on  "function saveBillingAction() "

    Check this line in this function and change

     From

       elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
                    $result['goto_section'] = 'shipping_method';
                    $result['update_section'] = array(
                        'name' => 'shipping-method',
                        'html' => $this->_getShippingMethodsHtml()
                    );

     To

       elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
                    $result['goto_section'] = 'payment';
                    $result['update_section'] = array(
                        'name' => 'payment-method',
                        'html' => $this->_getPaymentMethodsHtml()
                    );

 B)  Now, In Onepagecontroller.php

   Go to on this function  "public function saveShippingAction()"

  change this function

  From

   public function saveShippingAction()
    {
        if ($this->_expireAjax()) {
            return;
        }
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost('shipping', array());
            $customerAddressId = $this->getRequest()->getPost('shipping_address_id', false);
            $result = $this->getOnepage()->saveShipping($data, $customerAddressId);

            if (!isset($result['error'])) {
                $result['goto_section'] = 'shipping_method';
                $result['update_section'] = array(
                    'name' => 'shipping-method',
                    'html' => $this->_getShippingMethodsHtml()
                );
            }
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
        }
    }      


To

public function saveShippingAction()
    {
        if ($this->_expireAjax()) {
            return;
        }
        if ($this->getRequest()->isPost()) {
            $data = $this->getRequest()->getPost('shipping', array());
            $customerAddressId = $this->getRequest()->getPost('shipping_address_id', false);
            $result = $this->getOnepage()->saveShipping($data, $customerAddressId);

            if (!isset($result['error'])) {
                $result['goto_section'] = 'payment';
                $result['update_section'] = array(
                    'name' => 'payment-method',
                    'html' => $this->_getPaymentMethodsHtml()
                );
            }
            $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
        }
    }


C) After that Open Code/core/mage/sales/model/service/Quote.php

  Find this function " protected function _validate() "

  Here comment below code

  if ($addressValidation !== true) {
                Mage::throwException(
                    Mage::helper('sales')->__('Please check shipping address information. %s', implode(' ', $addressValidation))
                );
            }
            $method= $address->getShippingMethod();
            $rate  = $address->getShippingRateByCode($method);
            if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
                Mage::throwException(Mage::helper('sales')->__('Please specify a shipping method.'));
            }

D) Open file code/core/mage/checkout/block/onepage/shipping/Method.php

   This is hide the Shipping Method tab from the Onepage checkout during Place the order

   Find below function

    public function isShow()
    {
        return !$this->getQuote()->isVirtual();
    }

   Change it with

    public function isShow()
    {
                return false;
    }


   Now, Finally you can check that your Shipping Method will remove from your site.

  Enjoy ::





,