Chapters Close

Add Grand total in the shopping cart rule condition

Feb 12th, 2019 3 min to read
Table of Contents

When you are setting up a Shopping Cart Price Rule in Magento, you can choose a base condition on which the rule will apply on the subtotal. There are instances when the merchants may want to base the conditions on the final price, or the price that includes the subtraction of any other discounts applied. The code below shows how to add a grand total condition in Magento, which in this case will be a combination of the subtotal plus any discount applied.

A merchant may wish to set up the rule for the subtotal with the discount instead of the subtotal in case if they encounter any of the  scenarios given below:

  1. The merchant has an existing Shopping Cart Price Rule (Discount1), that provides a flat £10 discount off of the whole cart (no coupon code) if the customers’ subtotal is equal or greater than £100.
  2. The merchant also has an another Shopping Cart Price Rule (Discount2), that provides another flat £10 discount off of the whole cart, but requires a coupon code. This code will be applied if the customers’ subtotal is is equal or greater than £100.
  3. The customer adds a product that costs £100 and goes to the cart page.
  4. Discount1 has been applied automatically as the customer has met the criteria.
  5. The customer correctly enters in the coupon code from Discount2, and they receive another £10 discount, despite the subtotal staying at £100. The merchant may want the coupon code to only apply to the grand total, which because of Discount1, has dropped to £90.

#Magento 2

1. In your module, Ex:Companyname_Packagename, Create a di.xml file on the <root>/app/code/Companyname/Packagename/etc folder.

<type name="Magento\SalesRule\Model\Rule\Condition\Address">
        <plugin name="load-attribute-options" type="Companyname\Packagename\Plugin\Address" />
</type>

2. Now create a Address.php file at location <root>/app/code/Companyname/Packagename/Plugin folder.

<?php
namespace Companyname\Packagename\Plugin;

class Address
{
        public function afterLoadAttributeOptions(\Magento\SalesRule\Model\Rule\Condition\Address $subject)
    {
        $attributes = $subject->getAttributeOption();
        $attributes['base_subtotal_with_discount'] = __('Subtotal With Discount');
        $subject->setAttributeOption($attributes);
        return $subject;
    }

     public function afterGetInputType(\Magento\SalesRule\Model\Rule\Condition\Address $subject)
    {
        switch ($subject->getAttribute()) {
            case 'base_subtotal':
            case 'base_subtotal_with_discount':
            case 'weight':
            case 'total_qty':
                return 'numeric';

            case 'shipping_method':
            case 'payment_method':
            case 'country_id':
            case 'region_id':
                return 'select';
        }

        return 'string';
    }
}

3. Now execute the command given below in order to see the effective changes:

php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy en_US -f
php bin/magento cache:clean
php bin/magento cache:flush

4. The result will be as follows:

#Magento 1

<p>1. In your module, Ex:<code>Companyname_Packagename</code>, Create a <code>config.xml</code> file on the <code>/app/code/Companyname/Packagename/etc</code> folder.</p>

2. Now create Address.php file at location <root>/app/code/Companyname/Packagename/Model/SalesRule/Rule/Condition folder.

3. Assuming you’ve set up your module correctly, you should notice that the Subtotal With Discount option has been successfully added to the Conditions dropdown menu, and will be available for use if you wish to apply the rules that include a combination of subtotal along with the discounts.

4. That’s it, fellas! Here it goes:

How to setup Free Shipping in Magento 2?

Jan 7th, 2019 3 min to read

Free Shipping is one of the programs you can set up on Magento 2 when customers don’t need to pay any fee for the delivery. Free shipping makes them feel more comfortable and this is one marketing strategy that can encourage them to purchase more.

From Magento 2 Shopping Cart Rule settings, depending on the conditions you set, the Free Shipping can be applied for any order when all conditions are met.

Step 1: Activate Free Shipping

  • On the Admin Panel go to Stores > Settings > Configuration > Sales > Shipping Methods.
  • Open the Free Shipping section and follow the steps given below:
    • Enable the Free Shipping by choosing Yes.
    • Add the Title.
    • Enter the Method Name to make clear about the shipping method. For free shipping, type Free in the box.
    • Offer the Minimum Order Amount for the shipping.
    • Enter an error message in the Displayed Error Message box that will appear if Free Shipping is not available.
    • The Ship to Applicable Countries can be set to either of the two options:
      • All Allowed Countries: Free Shipping is supported for all the countries.
      • Specific Countries: Free Shipping is only supported for selected countries.
    • Set Show Method if Not Applicable to Yes if you want to show Free Shipping all the time.
    • Set the Sort Order on the Shipping Method on the checkout page.

Step 2: Activate Free Shipping in the Carrier Configuration

  • On the Admin Panel go to Stores > Settings > Configuration > Sales > Shipping Methods > UPS.
  • Set Free Method to “Ground.”
  • Enable the Free Shipping with Minimum Order Amount to the minimum amount of purchase for which free shipping is applicable in the Minimum Order Amount for Free Shipping field.

Step 3: Set a Shopping Cart Price Rule

On the Admin Panel Go to Marketing > Promotions > Cart Price Rules.

Apply Free Shipping for Any Order

  • In the Rule Information tab:
    • Set Name for the new rule and leave some descriptions of that.
    • Assign to the Website and Customer Group
    • Set Status to Active for which the rule is applied.
    • Set Coupon to No Coupon if shipping promotion is offered without any coupons.
  • In the Actions tab, open Pricing Structure Rules section:
    • Set Apply to Percent of product price discount
    • Set Apply to Shipping Amount to Yes
    • Set Free Shipping to For shipment with matching items.
  • In the Labels tab.
    • Under the Default Label section, insert the text in the Default Rule Label for All Store Views.
    • Under the Store View Specific Labels set the label for each store view.

Step 4: Check the Rule

After creating the rule you can test the rule right way to ensure that it is perfect.

How to create a shipping method in Magento 2?

Jul 17th, 2018 4 min to read
Table of Contents

This piece of information will throw some light on how one can create a shipping method in Magento 2.

For this, we need to create a custom module in order to add a new shipping method.

Step 1

Create a file named config.xml at app/code/Aureatelabs/Customshipping/etc/config.xml

<?xml version="1.0"?>
<config
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
	<default>
		<carriers>
			<alcustomshipping>
				<active>1</active>
				<allowed_methods>delivery</allowed_methods>
				<methods>delivery</methods>
				<sallowspecific>0</sallowspecific>
				<model>Aureatelabs\Customshipping\Model\Carrier</model>
				<name>Aureatelabs custom Shipping</name>
				<title>Aureatelabs custom Shipping</title>
				<handling_type>F</handling_type>
			</alcustomshipping>
		</carriers>
	</default>
</config>

This file is used for defining the shipping method code, which should be unique for each method.

Next, we need to define our model, which is already defined in config.xml under the <model> tag. Model is used for calculating our shipping cost.

app/code/Aureatelabs/Customshipping/Model/Carrier.php

<?php
namespace Aureatelabs\Customshipping\Model;

use Magento\Quote\Model\Quote\Address\RateResult\Error;
use Magento\Quote\Model\Quote\Address\RateRequest;
use Magento\Shipping\Model\Carrier\AbstractCarrierOnline;
use Magento\Shipping\Model\Carrier\CarrierInterface;
use Magento\Shipping\Model\Rate\Result;
use Magento\Shipping\Model\Simplexml\Element;
use Magento\Ups\Helper\Config;
use Magento\Framework\Xml\Security;

class Carrier extends AbstractCarrierOnline implements CarrierInterface
{
    const CODE = 'alcustomshipping';
    protected $_code = self::CODE;
    protected $_request;
    protected $_result;
    protected $_baseCurrencyRate;
    protected $_xmlAccessRequest;
    protected $_localeFormat;
    protected $_logger;
    protected $configHelper;
    protected $_errors = [];
    protected $_isFixed = true;

    public function __construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory, \Psr\Log\LoggerInterface $logger, Security $xmlSecurity, \Magento\Shipping\Model\Simplexml\ElementFactory $xmlElFactory, \Magento\Shipping\Model\Rate\ResultFactory $rateFactory, \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory, \Magento\Shipping\Model\Tracking\ResultFactory $trackFactory, \Magento\Shipping\Model\Tracking\Result\ErrorFactory $trackErrorFactory, \Magento\Shipping\Model\Tracking\Result\StatusFactory $trackStatusFactory, \Magento\Directory\Model\RegionFactory $regionFactory, \Magento\Directory\Model\CountryFactory $countryFactory, \Magento\Directory\Model\CurrencyFactory $currencyFactory, \Magento\Directory\Helper\Data $directoryData, \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry, \Magento\Framework\Locale\FormatInterface $localeFormat, Config $configHelper, array $data = [])
    {
        $this->_localeFormat = $localeFormat;
        $this->configHelper = $configHelper;
        parent::__construct($scopeConfig, $rateErrorFactory, $logger, $xmlSecurity, $xmlElFactory, $rateFactory, $rateMethodFactory, $trackFactory, $trackErrorFactory, $trackStatusFactory, $regionFactory, $countryFactory, $currencyFactory, $directoryData, $stockRegistry, $data);
    }
    protected function _doShipmentRequest(\Magento\Framework\DataObject $request)
    {
        // Do shipment request to carrier web service, obtain Print Shipping Labels and process errors in response
        
    }

    public function getAllowedMethods()
    {
        //Return shipping method unique code and its values from here.
        return [$this->_code => $this->getConfigData('name') ];
    }

    public function collectRates(RateRequest $request)
    {
        $result = $this
            ->_rateFactory
            ->create();

        /*store shipping in session*/
        $method = $this
            ->_rateMethodFactory
            ->create();
        $method->setCarrier($this->_code);
        $method->setCarrierTitle('Aureatelabs custom Shipping');
        /* Use method name */
        $method->setMethod($this->_code);
        $method->setMethodTitle('Aureatelabs Custom Shipping');
        $method->setCost(10);
        $method->setPrice(10);
        $result->append($method);
        return $result;
    }

    public function proccessAdditionalValidation(\Magento\Framework\DataObject $request)
    {
        return true;
    }
}

After this you can see that the shipping method will get displayed at the frontend.

In order to define custom setting for shipping method, we need to create system.xml , which is located at the path given below:

app/code/Aureatelabs/Customshipping/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
	<system>
		<section id="carriers" translate="label" type="text" sortOrder="320" showInDefault="1" showInWebsite="1" showInStore="1">
			<group id="alcustomshipping" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
				<label>Aureatelabs Custom Shipping Method</label>
				<field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0">
					<label>Enabled</label>
					<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
				</field>
				<field id="title" translate="label" type="text" sortOrder="2" showInDefault="1" showInWebsite="1" showInStore="1">
					<label>Title</label>
				</field>
				<field id="name" translate="label" type="text" sortOrder="3" showInDefault="1" showInWebsite="1" showInStore="1">
					<label>Name</label>
				</field>
				<field id="sallowspecific" translate="label" type="select" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">
					<label>Ship to Applicable Countries</label>
					<frontend_class>shipping-applicable-country</frontend_class>
					<source_model>Magento\Shipping\Model\Config\Source\Allspecificcountries</source_model>
				</field>
				<field id="specificcountry" translate="label" type="multiselect" sortOrder="7" showInDefault="1" showInWebsite="1" showInStore="0">
					<label>Ship to Specific Countries</label>
					<source_model>Magento\Directory\Model\Config\Source\Country</source_model>
					<can_be_empty>1</can_be_empty>
				</field>
			</group>
		</section>
	</system>
</config>

Now please visit to Stores > Settings > Configuration > Sales > Shipping Methods.

Grow your online business like 2,119 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.