Thursday, 4 June 2020

Magento2 Checkout shipping address autofill

Magento2 Checkout shipping address autofill

Magento2 Checkout shipping address autofill.

If you want to Magento2 Checkout shipping address autofill during checkout then you have to use Magento 2 plugin.

I have used plugin over on Class below classes for autofill checkout Shipping address:

Magento\Checkout\Block\Checkout\AttributeMerger::merge
Magento\Checkout\Model\DefaultConfigProvider::getConfig

Magento\Checkout\Block\Checkout\AttributeMerger is  main classis the main class where i able to auto fill firstname,lastname,street,city,postcode,country_id,region,region_id,telephone,companyabove fields value using after

Create after Plugin (Devbera\AutofillCheckoutAddress\Plugin\Magento\Checkout::afterMerge ) on Magento\Checkout\Block\Checkout\AttributeMerger::merge for shipping address fields autofill up.

Step1:Define Plugin classes:

First Create di.xml at app/code/{VendorName}/{ModuleName}/etc/frontent where we are define the plugin classes.

Code

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Checkout\AttributeMerger">
        <plugin disabled="false" name="checking_shipping_address_auto_full"
                sortOrder="10" type="{VendorName}\{ModuleName}\Plugin\Magento\Checkout\AttributeMergerPlugin"/>
    </type>
    <type name="Magento\Checkout\Model\DefaultConfigProvider">
        <plugin disabled="false" name="checking_email_auto_full" sortOrder="10"
                type="{VendorName}\{ModuleName}\Plugin\Magento\Checkout\Model\DefaultConfigProviderPlugin"/>
    </type>
</config>

Step2: Declare plugin class

Create First plugin class AttributeMergerPlugin.php at app/code/{VendorName}/{ModuleName}/Plugin/Magento/Checkout/

Code

<?php
/**
 * @category   Devbera
 * @package    Devbera_AutofillCheckoutAddress
 * @author     Amit Bera <dev.amitbera@gmail.com>
 * @website    http://www.amitbera.com
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

namespace {VendorName}\{ModuleName}\Plugin\Magento\Checkout;

class AttributeMergerPlugin
{
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    public function __construct(
        \Psr\Log\LoggerInterface $logger
    ) {
        $this->logger = $logger;
    }

    public function afterMerge(
        \Magento\Checkout\Block\Checkout\AttributeMerger $subject,
        $fields
    ) {
        $this->logger->info(__METHOD__);
        
        $fieldNames = $this->shippingAddressFieldAnAutoFillValues();

        foreach ($fields as $attributeCode => $field) {
            //$this->logger->info(print_r($field, true));
            if (in_array($attributeCode, $fieldNames)) {
                //  Different Code for set Value for Street
                if ($attributeCode == 'street' &&
                    isset($field['children'][0]['config']['customScope'])
                    && $field['children'][0]['config']['customScope'] == 'shippingAddress') {
                    $fields[$attributeCode]['children'][0]['value'] = 'Oregon State University';
                }
                // Checking Address Type Shipping and Attribute is not Street
                if ($attributeCode != 'street' &&
                    (isset($field['config']['customScope']) && ($field['config']['customScope'] == 'shippingAddress'))) {
                    
                     $this->logger->info($attributeCode);
                    switch ($attributeCode) {
                        case "firstname":
                            $fields[$attributeCode]['value'] = 'John';
                            break;
                        case "lastname":
                            $fields[$attributeCode]['value'] = 'Deo';
                            break;
                        case "city":
                            $fields[$attributeCode]['value'] = 'Corvallis';
                            break;
                        case "country_id":
                            $fields[$attributeCode]['value'] = 'US';
                            break;
                        case "region_id":
                            $fields[$attributeCode]['value'] = 49;
                            break;
                        case "telephone":
                            $fields[$attributeCode]['value'] = '+1 541-737-1000';
                            break;
                        case "company":
                            $fields[$attributeCode]['value'] = 'Public school';
                            break;
                        case "postcode":
                            $fields[$attributeCode]['value'] = '973331';
                            break;
                        case "region":
                            $fields[$attributeCode]['value'] = 'Oregon';
                            break;
                        default:
                           // echo "ELSE";
                    }
                }
            }
        }
        return $fields;
    }

    /**
     * Makeing an array of
     * @return array
     */
    private function shippingAddressFieldAnAutoFillValues()
    {
        return [
            'firstname',
            'lastname',
            'city' ,
            'postcode',
            'country_id',
            'region',
            'region_id' ,
            'telephone',
            'street',
            'company'
        ];
    }
 
}

Second plugin class which will auto fill email id for NON _login customer

Create seocnf plugin class DefaultConfigProviderPlugin.php at app/code/{VendorName}/{ModuleName}/Plugin/Magento/Checkout/Modelt/

<?php
/**
 * @category   Devbera
 * @package    Devbera_AutofillCheckoutAddress
 * @author     Amit Bera <dev.amitbera@gmail.com>
 * @website    http://www.amitbera.com
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

namespace {VendorName}\{ModuleName}\Plugin\Magento\Checkout\Model;

use Magento\Framework\App\Http\Context as HttpContext;
use Magento\Customer\Model\Context as CustomerContext;

class DefaultConfigProviderPlugin
{
    /**
     * @var HttpContext
     */
    private $httpContext;

    public function __construct(
        HttpContext $httpContext
    ) {
        $this->httpContext = $httpContext;
    }

    public function afterGetConfig(
        \Magento\Checkout\Model\DefaultConfigProvider $subject,
        $result
    ) {
        if (!$this->isCustomerLoggedIn() && is_array($result)) {
            $result['validatedEmailValue'] = 'john.deo@gmail.com';
        }
        return $result;
    }
    /**
     * Check if customer is logged in
     *
     * @return bool
     * @codeCoverageIgnore
     */
    private function isCustomerLoggedIn()
    {
        return (bool)$this->httpContext->getValue(CustomerContext::CONTEXT_AUTH);
    }
}

Disabled Autofill fields

If you want to disallow this autofill fields from editable for the customer then you have to add below code

$fields[$attributecode]['disabled'] = true; 

after autofill value set like you want disable first name field disable for customer after auto fill then add below code:

case "firstname":
    $fields[$attributeCode]['value'] = 'John';
    // Disable first  name field 
    $fields[$attributecode]['disabled'] = true; 		
    break;
case "lastname":
    $fields[$attributeCode]['value'] = 'Deo';
    break

Autofills Street field

Here, you may be seen that I have used different condition for the street because of this field is multiline code field. By default Magento street field is two lines, then you can use below code

 $fields[$attributecode]['children'][1]['value'] = 'Mayer road';

Here , at associated array value is 1 ( [‘children’][1]) as its line no is 2.


No comments:

Post a Comment

  How to Upgrade magento version from 2.3.x [EE] to 2.3.x [EE] Here are the steps I used to successfully update Magento 2.3.3 [EE] to 2.3.5 ...