PHP SOLUTIONS

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

Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts

Monday, 11 April 2016

Magento : Add last increment id of "sales_flat_quote_item" in another table

Magento
        $production = Mage::getSingleton('core/session')->getproValue($production); /* This is the session value which is set on Category/List page */
        $shipping = Mage::getSingleton('core/session')->getshipValue($ship);  /* This is the session value which is set on Category/List page */

/* This is code for Change Row Data of the product in cart and add Shipping charge in to that product into cart
         * Changes By Rixit
        // */
       
            $connection = Mage::getSingleton('core/resource')
            ->getConnection('core_read');
            $select = $connection->select()
            ->from('sales_flat_quote_item', array('MAX(item_id) as itn')); // select * from tablename or use array('id','name') selected values  
            $rowsArray = $connection->fetchAll($select); // return all rows
            $rowArray =$connection->fetchRow($select);   //return row
       
            $temp = $rowArray['itn'];
           
            $select1 = $connection->select()
            ->from('sales_flate_lastinsertd_id', array('MAX(last_inserted_id) as itn1')); // select * from tablename or use array('id','name') selected values  
            $rowsArray = $connection->fetchAll($select1); // return all rows
            $rowArray =$connection->fetchRow($select1);   //return row
       
            $itnew = $rowArray['itn1'];
       
            if( ($temp != $itnew) && ($temp >= $itnew) )
            {   
                $total = $production + $shipping;
       
                $connection = Mage::getSingleton('core/resource')
                ->getConnection('core_write');
       
                $connection->beginTransaction();
                $fields = array();
                $fields['last_inserted_id']= $temp;
                $fields['production_time']= $production;
                $fields['shipping_time']= $shipping;        
                $fields['total']= $total;        
                $connection->insert('sales_flate_lastinsertd_id', $fields);
                $connection->commit();
                               
            }
            else
            {
                //echo "Riisdfs";
            }
           
        /*
         * End of Changes By Rixit
        // */

Thursday, 7 April 2016

Magento 2 : CSS and Javascript no loading after installation

    This is an initial issue with magento 2, After Installation Front-End and Back-End CSS / JS do not work.

    Using following steps, it is getting work easily for magento 2 !

    This is creating frontend / adminhtml directory to the "pub/static/" directory.

Using Command Prompt(CMD) set CSS & JS for Magento2

Step 1 : Run CMD

Step 2 : Goto Magento installation directory using

             CD wamp/www/[Magento dir.]

Step 3 : Run

             php bin/magento setup:static-content:deploy

             If you are getting problem of

            "php is not recognized as an internal or external command" [Click here...]

Step 4 : Run

             php bin/magento indexer:reindex

Step 5 : Delete Cache from

             var/cache/[delete all dir.]

It's getting work for Front-end & Back-end !

Tuesday, 9 June 2015

Magento : Update cart price using the observer event

Hello Friends,

Using Observer,we have seen how to set the custome price, Check Here

Now, We are going for update the product with the custome price, because in magento, for the set any custome price, update custome price, there are different Observer Events which is help us for making proper customization.

A) Open Module Config.xml file which is located at etc directory of Module
[This module is same which we use for the Set Custome price]

B) Here, the code of observer event for update price

Magento

<frontend>
...................
<events>
 <checkout_cart_product_update_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>updatecustomprice</method>
   </{Namespace}_{Module Name}__Model_Observer>
  </observers>
 </checkout_cart_product_update_after>
</events>
.................
</frontend>
C) Now, Create or Update [if alreay you have] Observer.php in Model Directory
{Namespace}/{Module Name}/Model/Observer.php
D) In Observer.php add updatecustomprice function

Magento

class {Namespace}/{Module Name}_Model_Observer
{

public function updatecustomprice(Varien_Event_Observer $observer) {

$item = $observer->getQuoteItem();
$custom_vals = $_SESSION['custom_vals'];
if($custom_vals != '')
{
$additionalOptions = array(array(
'label' => '',
'value' => $custom_vals,
));
$item->addOption(array(
'code' => 'additional_options',
'value' => serialize($additionalOptions),
));
unset($_SESSION['custom_vals']);
}
$price = 123; //Here, set the Custom Price for Item
$item->setCustomPrice($price); // This set the Custom Price in Quote of cart
$item->setOriginalCustomPrice($price);
$item->getProduct()->setIsSuperMode(true);
}

}
E) Now, Clear all cache of site from admin

Enjoy, This is work for me in Magento 1.7.0.2

Thursday, 16 April 2015

Magento : Display product image in order transaction mail


Hi, Some Time client want some extra, just like here,
For set Product image with the mails in Magento you need to follow just 2 change for that
1) File for Edit : app/design/frontend/base/default/template/email/order/items.phtml
   After the below mentioned line
  <th align="left" bgcolor="#EAEAEA" style="font-size:13px; padding:3px 9px"><?php echo $this->__('Sku') ?></th>
  Add this,
  <th align="left" bgcolor="#EAEAEA" style="font-size:13px; padding:3px 9px"><?php echo $this->__('Image') ?></th>

2) File for Edit : 
app/design/frontend/base/default/template/email/order/items/order/default.phtml

   After the below mentioned line
  
<td align="left" valign="top" style="font-size:11px; padding:3px 9px; border-bottom:1px dotted #CCCCCC;"><?php echo $this->escapeHtml($this->getSku($_item)) ?></td>


  Add this,
        <td align="center" valign="top" style="font-size:11px; padding:3px 9px; border-bottom:1px dotted #CCCCCC;">
                  <img src="<?php echo $this->helper('catalog/image')->init(Mage::getModel('catalog/product')->load($_item->getProductId()), 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->htmlEscape($_item->getName()) ?>" />
      </td>

Now, Go to admin and Clear Cache, Make Order you got the Product image also with order !

Wednesday, 9 July 2014

Magento : Add Meta Title field in CMS pages

In this Blog I written about to set the Meta title field inside the CMS Page.

Here, Some steps need to follow for Meta Title Field

1) Open File Meta.php

   Location = /app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/Meta.php

2) Copy - Paste this code after

    $fieldset = $form->addFieldset('meta_fieldset', array('legend' => Mage::helper('cms')->__('Meta Data'), 'class' => 'fieldset-wide'));

    /*Copy*/

    $fieldset->addField('meta_title', 'text', array(
            'name' => 'meta_title',
            'label' => Mage::helper('cms')->__('Title),
            'title' => Mage::helper('cms')->__('Meta Title'),
            'disabled'  => $isElementDisabled
        ));

3)  Open Database - Go to table - cms_page

4)  write this query

     ALTER TABLE `cms_page` ADD `meta_title` VARCHAR(100) NOT NULL AFTER `root_template`;


Now, Check any CMS page in admin side !!


Monday, 31 March 2014

Magento Images not displayed in Admin

HI,

    Some times in Magento create amazing issues, in admin or for fornt end also

    Recently, I am getting this type of issue, In side admin I can't see the product images after the Inserting the product

Product Images no display in admin


for solve this type of issue

Just open media directory using FTP and just change the name of .htaccess to .htaccess_old

And you have solve the Image issue.

Enjoy::::

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 ::





Monday, 31 December 2012

Magento : Change price in cart programatically

Hi,

  Here for change the product price into cart programatically

  There is an simple way for change this product price and add custom price for the specific product into cart when add the product into cart in magento.

1) Create an Attribute for the products,

   Suppose an Ex. is Change Price
   Set its type yes/no for the product

2) Open File, code/core/mage/checkout/model/cart.php

3) Goto on this function,

     public function save()
    {
      ........
      ........
     }

4) Copy and Paste below code,

    public function save()
    {
        Mage::dispatchEvent('checkout_cart_save_before', array('cart'=>$this));

        $this->getQuote()->getBillingAddress();
        $this->getQuote()->getShippingAddress()->setCollectShippingRates(true);
        $this->getQuote()->collectTotals();
              
        foreach($this->getQuote()->getAllItems() as $item) {            
          $productId = $item->getProductId();
          $product = Mage::getModel('catalog/product')->load($productId);
          if($product->getAttributeText('change_price') == 'Yes')
         {
                 $price = 5;
                 $item->setCustomPrice($price);
                 $item->setOriginalCustomPrice($price);
          }
        } 
        $this->getQuote()->save();
        $this->getCheckoutSession()->setQuoteId($this->getQuote()->getId());
       
        /**
         * Cart save usually called after changes with cart items.
         */
        Mage::dispatchEvent('checkout_cart_save_after', array('cart'=>$this));
        return $this;
      }

5) Now, Insert Product form Admin and set its Change Price value yes for that product,

6) Add that product to cart you can see that, product Unit price will change to $5.

   This is work for me in 1.7.0.2

 Enjoy!!!!!

Monday, 24 December 2012

Magento : Get custom options on category page

 Here, The Code for get Custom Options of Products on category Page, This is useful for reduce the time for customer purchase product and add to cart it, there is another methods are also but in that we can't add product with it's custom options, so using this we can add product to cart with its custom options.


 <?php
    $sandy = "";
    $attVal = $product->getOptions();
    if(sizeof($attVal))
    {
          foreach($attVal as $optionVal)
          {   
        $type = $optionVal->getType();
        if($type != 'field' && $type != 'file' )
         {
                $sandy .= $optionVal->getTitle().": ";
                $sandy .= "<select id='select_".$optionVal->getId()."' name='options[".$optionVal->getId()."]'>";
                foreach($optionVal->getValues() as $valuesKey => $valuesVal)
            {           
                if($valuesVal->getPrice() != "0.00000")
                {
                      $sandy .= "<option price='".$valuesVal->getPrice(true)."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle() .'+'.  $valuesVal->getPrice(true) ."</option>";       
                  }
                  else
                  {
                $sandy .=  "<option price='".$valuesVal->getPrice(true)."' value='".$valuesVal->getId()."'>".$valuesVal->getTitle() ."</option>";
                }
            }
            $sandy .= "</select>";
        }
        else if($type == 'file')
        {
            $sandy .= $optionVal->getTitle().": ";
                $sandy .= "<input type='file' name='options_".$optionVal->getId()."_file'>";               
              }
        else
        {
            $sandy .= $optionVal->getTitle() ."  : ";
                $sandy .= "<input type='text' name='options[".$optionVal->getId()."]' id='options_".$optionVal->getId()."_text' onchange='javascript: getval();'>";                  
        }
        }
    }
    echo $sandy;
  ?>

  <?php echo $this->getPriceHtml($_product, true) ?>
    
  <?php if(!$_product->isGrouped()): ?>
  <label>Qty:</label>
        <input type="text" id="qty_main" maxlength="12" value="<?php echo $this->getMinimalQty($_product)==null?1:$this->getMinimalQty($_product) ?>" onblur="calculatetotal();"/>
        <button type="submit" id="addtocartbt_<?php echo $_product->getSku(); ?>" onclick="productAddToCartForm<?php echo $_product->getId() ?>.submit()">Add to Cart</button>
  <?php endif; ?>  
  </div>
                                        
  </form>
      
<script type="text/javascript">
       
var productAddToCartForm<?php echo $_product->getId() ?> = new VarienForm('product_addtocart_form_<?php echo $_product->getId() ?>');                       
    productAddToCartForm<?php echo $_product->getId() ?>.submit = function()
    {
            if (this.validator.validate())
        {   
            this.form.submit();                           
            }                   
        }.bind(productAddToCartForm<?php echo $_product->getId() ?>);
  </script>
  <?php else: ?>
      <div class="out-of-stock"><?php echo $this->__('Out of stock') ?></div>
  <?php endif; ?>

Wednesday, 28 November 2012

Magento : Remove TAX / VAT from grand total in checkout


Here, We can Remove Tax from Grand Total.

If we want to removed tax for all customer we simply remove Tax class from the produc's then It will remove automatically.

But If you want to remove Tax for specific customer you can do using below steps.

Here Example for Remove Tax for that Customer Who have their Business VAT Numbers.

1) Goto " app/code/core/mage/tax/model/calculation.php  "

2) Find this Function "  public function getRateRequest() "

3) You can get this at the end of the function

    $request = new Varien_Object();
        $request
            ->setCountryId($address->getCountryId())
            ->setRegionId($address->getRegionId())
            ->setPostcode($address->getPostcode())
            ->setStore($store);
            ->setCustomerClassId($customerTaxClass);

4) Now Here for who have VAT/TAX numbers, no apply Tax in Grand Total

    $eutax = $customer['taxvat'];

    if($eutax != '')
   {
            //Who have to insert their VAT Number then remove TAX from Grand Total
            $request = new Varien_Object();
            $request
                       ->setCountryId($address->getCountryId())
                       ->setRegionId($address->getRegionId())
                       ->setPostcode($address->getPostcode())
                       ->setStore($store);                      
    }
    else
    {
           //Who have to not insertd their VAT Number then add TAX in Grand Total
           $request = new Varien_Object();
           $request
                      ->setCountryId($address->getCountryId())
                      ->setRegionId($address->getRegionId())
                      ->setPostcode($address->getPostcode())
                      ->setStore($store);
                      ->setCustomerClassId($customerTaxClass);


    }

5) Now check Tax is Remove from Grand Total in checkout.


Saturday, 24 November 2012

Magento : Upgrade Magento version



You can do this for Upgrade Magento 1.4 to 1.7

Do this in your Local Machine because when you Upgrade Do not reload page before complete all steps

1) Backup your current Site files and Database

2) Download Newer version from http://www.magentocommerce.com/download
    then Extract that zip in Directory

3) Upload or Override newer version files on your current site files

4) your database upgrade automatically so don't do any thing with that

5) After Complete override then remove site cache and index from admin

6) Now, Reload your site, you can see Upgraded version 1.7 in footer


Saturday, 17 November 2012

Magento : Add JavaScript / CSS



There is Two way for add external Javascript in magento

1) Using Page.xml
2) Using Head.phtml


1) Using Page.xml :::\\//

<action method="addJs"><script>directoryname/javascript_name.js</script></action>


2) Using Head.phtml :::\\//

<script type="text/javascript" src="<?php echo $this->getSkinUrl('directoryname/javascript_name.js') ?>"></script>

<link href='<?php echo $this->getSkinUrl('directoryname/css_name.css')  ?>' rel='stylesheet' type='text/css' />

Magento : Get popular tags list for any page


Here, I get Popular Tags List on Any page,

Using this can get HTML Layout of the Phtml page

Simply, Copy and Paste below code


<?php echo $this->getLayout()->createBlock('tag/popular')->setTemplate('tag/popular.phtml')->toHtml(); ?>


If you want another page html then change block directory and type,

also replace template name of phtml file.