How can i add a driver tip in magento onepage chec

2020-06-05 01:37发布

问题:

Currently i have an requirement of adding a custom Driver tip step in magento onepage checkout process, right after the shipping method(step-3), in which i want user to select tip from some given options(i will make radio buttons), that will contain certain amounts, suppose user selected $150 then this amount will be added into total payment ? i tried all other tutorials over google, none of them is working for me, any help is appreciated,

回答1:

I recently work on similar type of requirement. so follow my instructions:-

I request to you that don't focus on the length of answer just focus on the result

step 1:-if you want to put Driver tip between shipping and shipping method then first open

\app\code\core\Mage\Checkout\Block\Onepage.php there is an array $stepCodes (line no:- 44). replace that with this

$stepCodes = array('billing', 'shipping', 'excellence2','shipping_method', 'payment', 'review'); 

i am using excellence2 you can also use this name.

Step 2:- now we need to create Excellence2 class on app\code\core\Mage\Checkout\Block\Onepage\ so create a new php file and put that code into it and save as Excellence2.php

class Mage_Checkout_Block_Onepage_Excellence2 extends Mage_Checkout_Block_Onepage_Abstract
{
protected function _construct()
{
    $this->getCheckout()->setStepData('excellence2', array(
        'label'     => Mage::helper('checkout')->__('Tip Ammount'),
        'is_show'   => $this->isShow()
    ));
    parent::_construct();

}
}

Note:- now you can put any name at label of _construct() function so change 'Tip Ammount' to Driver tip

Step 3:-now open OnepageController.php which is located in app\code\core\Mage\Checkout\controllers\ and find saveBillingAction() function (line no:-296) and replace that code by this

 public function saveBillingAction()
{       
    if ($this->_expireAjax())
      {
        return;
      }
    if ($this->getRequest()->isPost()) {
        //            $postData = $this->getRequest()->getPost('billing', array());
        //            $data = $this->_filterPostData($postData);
        $data = $this->getRequest()->getPost('billing', array());
        $customerAddressId = $this->getRequest()->getPost('billing_address_id', false);

        if (isset($data['email'])) {
            $data['email'] = trim($data['email']);
        }
        $result = $this->getOnepage()->saveBilling($data, $customerAddressId);

        if (!isset($result['error'])) {
            /* check quote for virtual */
            if ($this->getOnepage()->getQuote()->isVirtual()) {
                $result['goto_section'] = 'payment';
                $result['update_section'] = array(
                    'name' => 'payment-method',
                    'html' => $this->_getPaymentMethodsHtml()
                );
            } elseif (isset($data['use_for_shipping']) && $data['use_for_shipping'] == 1) {
                $result['goto_section'] = 'excellence2';  //Goes to our step
                $result['allow_sections'] = array('shipping');
                $result['duplicateBillingInfo'] = 'true';
            } else {
                $result['goto_section'] = 'shipping';
            }
        }

        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
}

Step 4:- again in same file OnepageController.php there is a saveShippingAction() function (line no 331) change this 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'] = 'excellence2'; //Go to our step
        }
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
    }
  }

this code tells that when user pass though the shipping step then he will go to our Driver tip step.

Step 5:-again in same file (OnepageController.php) we need to tell that where user will redirect after pass though Driver tip step .so create a saveExcellence2Action() just after saveShippingAction() function

public function saveExcellence2Action()
{
    if ($this->_expireAjax()) {
        return;
    }
    if ($this->getRequest()->isPost()) {
        $data = $this->getRequest()->getPost('excellence2', array());

        $result = $this->getOnepage()->saveExcellence2($data);

        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));
    }
}

Step 6:- now we change in checkout.xml which is located in

\app\design\frontend\default\your template\layout open it and find

<checkout_onepage_index translate="label">

and in that particular node there is block (line no 326)

<block type="checkout/onepage_shipping" name="checkout.onepage.shipping" as="shipping" template="checkout/onepage/shipping.phtml"/>

just add a new block after this line shown above

<block type="checkout/onepage_excellence2" name="checkout.onepage.excellence2" as="excellence2" template="checkout/onepage/excellence2.phtml"/>

Step 7:- now we need to create a excellence2.phtml file at \app\design\frontend\default\your template\template\checkout\onepage\

this file show the content which you want to show to user

<form id="co-excellence2-form" action="">
<div class="wide"> <label for="excellence2:like" class="required"><em  style="color:#F00;">*</em>&nbsp;&nbsp;&nbsp;Select the amount of tip ,You wish to give to the driver.</label>
</div>
<div style="margin-top:20px;">
<ul>
<li>
<input type="radio" name="excellence2[like]" id="excellence2:like" value="0" checked="checked" class="radio" onclick="savevalue(this.value);"/>&nbsp;&nbsp;&nbsp;No Tip/Pay driver at the door
</li>
<li>
<input type="radio" name="excellence2[like]" id="excellence2:like" value="150" class="radio" onclick="savevalue(this.value);" />&nbsp;&nbsp;&nbsp;150$
</li>
<li>
<input type="radio" name="excellence2[like]" id="excellence2:like" value="250" class="radio"  onclick="savevalue(this.value);"/>&nbsp;&nbsp;&nbsp;250$
</li>
<li>
<input type="radio" name="excellence2[like]" id="excellence2:like" value="400" class="radio" onclick="savevalue(this.value);" />&nbsp;&nbsp;&nbsp;400$
</li>
<li>
<input type="radio" name="excellence2[like]" id="excellence2:like" value="500" class="radio"  onclick="savevalue(this.value);"/>&nbsp;&nbsp;&nbsp;500$
</li>
<li>
<input type="radio" name="excellence2[like]" id="excellence2:like" value="15% of total amount" class="radio" onclick="savevalue(this.value);" />&nbsp;&nbsp;&nbsp;15% of Total Amount
</li>
</ul>
</div>
<fieldset>
<div class="buttons-set" id="excellence2-buttons-container">
<p class="required"><?php echo $this->__('* Required Fields') ?></p>
<button type="button" title="<?php echo $this->__('Continue') ?>" class="button" onclick="excellence2.save()"><span><span><?php echo $this->__('Continue') ?></span></span>    
</button>
<span class="please-wait" id="excellence2-please-wait" style="display:none;">
<img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo $this->__('Loading next step...') ?>" title="<?php echo $this->__('Loading next step...') ?>" class="v-middle" /> <?php echo $this->__('Loading next step...') ?>
</span>
</div>
</fieldset>
</form>
<script type="text/javascript">
//<![CDATA[
var excellence2 = new ExcellenceMethod2('co-excellence2-form','<?php echo  $this->getUrl('checkout/onepage/saveExcellence2') ?>');
var excellenceForm2 = new VarienForm('co-excellence2-form');
//]]>

</script>

Step 8:-now we need to create a excellencecheckout.js file at \skin\frontend\default\your template\js

var ExcellenceMethod2 = Class.create();
ExcellenceMethod2.prototype = {
initialize: function(form, saveUrl){
    this.form = form;
    if ($(this.form)) {
        $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
    }
    this.saveUrl = saveUrl;
    this.validator = new Validation(this.form);
    this.onSave = this.nextStep.bindAsEventListener(this);
    this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
},

validate: function() {

    return true;
},

save: function(){

    //alert('hi');
    if (checkout.loadWaiting!=false) return;
    if (this.validate()) {
        checkout.setLoadWaiting('excellence2');
        var request = new Ajax.Request(
            this.saveUrl,
            {
                method:'post',
                onComplete: this.onComplete,
                onSuccess: this.onSave,
                onFailure: checkout.ajaxFailure.bind(checkout),
                parameters: Form.serialize(this.form)
            }
        );
    }
},

resetLoadWaiting: function(transport){
    checkout.setLoadWaiting(false);
},

nextStep: function(transport){
    if (transport && transport.responseText){
        try{
            response = eval('(' + transport.responseText + ')');
        }
        catch (e) {
            response = {};
        }
    }

    if (response.error) {
        alert(response.message);
        return false;
    }

    if (response.update_section) {
        $('checkout-'+response.update_section.name+'-load').update(response.update_section.html);
    }


    if (response.goto_section) {
        //alert(response);
        checkout.gotoSection(response.goto_section);
        checkout.reloadProgressBlock();
        return;
    }

    checkout.setPayment();
}
}

Step 9:- now we need to create a new function for save data which user was selected . so we are creating new function which name is saveExcellence2() just after the saveShipping($data, $customerAddressId) finction in Onepage.php which is located in \app\code\core\Mage\Checkout\Model\Type\

public function saveExcellence2($data)
{
    if (empty($data)) 
    {
        return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
    }
    $this->getQuote()->setExcellenceLike2($data['like']);
    $this->getQuote()->collectTotals();
    $this->getQuote()->save();

    $this->getCheckout()

    ->setStepData('excellence2', 'complete', true)
    ->setStepData('shipping_method', 'allow', true);

    return array();
}


回答2:

By default magento gives some checkout steps. But Sometime you need to add extra information from the customer for future reference. A common requested customization is to add the Custom Form in default checkout process. This is not good practice to touch core files. You can do this via overriding Modules. In this example Comapnyname is Ipragmatech and Module name is Checkoutstep.

Step1: Add Custom step in the checkout process

Open the Ipragmatech > Checkoutstep > Block > Onepage> Checkoutstep.php file and write the following code

    class Ipragmatech_Checkoutstep_Block_Onepage_Checkoutstep extends Mage_Checkout_Block_Onepage_Abstract
    {
       protected function _construct()
       {     
          $this->getCheckout()->setStepData('checkoutstep', array(
          'label'     => Mage::helper('checkout')->__('Invitation to participation'),
          'is_show'   => true
        ));
        parent::_construct();
       }
     }

Step2: Add steps which and where you want in the checkout process

Open the Ipragmatech > Checkoutstep > Block > Onepage> Checkoutstep.php file and write the following code

    class Ipragmatech_Checkoutstep_Block_Onepage extends Mage_Checkout_Block_Onepage
    {
      public function getSteps()
      {
             $steps = array();

             if (!$this->isCustomerLoggedIn()) {
                $steps['login'] = $this->getCheckout()->getStepData('login');
             }

            $stepCodes = array('billing', 'shipping', 'shipping_method', 'payment', 'checkoutstep', 'review');
         foreach ($stepCodes as $step) {
             $steps[$step] = $this->getCheckout()->getStepData($step);
          }

    return $steps;
   }
}

Step3: Grab the submitted value of custom form and set the values of Custom form

Open the ipragmatech > Checkoutstep > controllers > OnepageController.php and write the following fucntion

    public function saveCheckoutstepAction()
    {
      $this->_expireAjax();
      if ($this->getRequest()->isPost()) {

     //Grab the submited value 
     $_entrant_name = $this->getRequest()->getPost('entrant_name',"");
     $_entrant_phone = $this->getRequest()->getPost('entrant_phone',"");
     $_entrant_email = $this->getRequest()->getPost('entrant_email',"");
     $_permanent_address = $this->getRequest() ->getPost('permanent_address',"");
     $_address = $this->getRequest()->getPost('local_address',"");

     Mage::getSingleton('core/session') ->setIpragmatechCheckoutstep(serialize(array(
    'entrant_name' =>$_entrant_name,
    'entrant_phone' =>$_entrant_phone,
    'entrant_email' =>$_entrant_email,
    'permanent_address' =>$_permanent_address,
    'address' =>$_address
     )));

    $result = array();
    $redirectUrl = $this->getOnePage()->getQuote()->getPayment() ->getCheckoutRedirectUrl();
        if (!$redirectUrl) {
            $this->loadLayout('checkout_onepage_review');
            $result['goto_section'] = 'review';
            $result['update_section'] = array(
                'name' => 'review',
                'html' => $this->_getReviewHtml()
            );

        }

        if ($redirectUrl) {
            $result['redirect'] = $redirectUrl;
        }

        $this->getResponse()->setBody(Zend_Json::encode($result));
    }
}

Step4: Save Custom Form information

When checkout_onepage_controller_success_action event hook is called. Open the Ipragmatech > Checkoutstep > Model >Observer.php and write the following

    class Ipragmatech_Checkoutstep_Model_Observer {
      const ORDER_ATTRIBUTE_FHC_ID = 'checkoutstep';
      public function hookToOrderSaveEvent() {
      if (Mage::helper('checkoutstep')->isEnabled()) {
         $order = new Mage_Sales_Model_Order ();
         $incrementId = Mage::getSingleton ( 'checkout/session' )->getLastRealOrderId ();
         $order->loadByIncrementId ( $incrementId );

       // Fetch the data 
       $_checkoutstep_data = null;
       $_checkoutstep_data = Mage::getSingleton ( 'core/session' )->getIpragmatechCheckoutstep ();
       $model = Mage::getModel ( 'checkoutstep/customerdata' )->setData ( unserialize ( $_checkoutstep_data ) );
       $model->setData ( "order_id",$order["entity_id"] );
       try {
           $insertId = $model->save ()->getId ();
             Mage::log ( "Data successfully inserted. Insert ID: " . $insertId, null, 'mylog.log');
        } catch ( Exception $e ) {
            Mage::log ( "EXCEPTION " . $e->getMessage (), null, 'mylog.log' );
          }
        }
    }

}

Magento – Add Custom Form in Checkout Extension is a complete solution to add extra step in Checkout process for your ecommerce website. It allow admin to export data from custom table in CSV format. Visit the link to get this free extension http://www.magentocommerce.com/magento-connect/custom-form-in-checkout.html