0

Can we populate the default country and postcode for the logged in users using their default shipping address of the customer to get shipping estimates?

1

You can create Block in your Custom module and call method getShipping() to get all data of Shipping address from your phtml file as below:

<?php 
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;

class Shipping extends Template
{

    protected $_addressFactory;
    protected $customerSession;
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\AddressFactory $addressFactory,
        \Magento\Customer\Model\SessionFactory $customerSession
    ) {

            $this->_addressFactory = $addressFactory;
            $this->customerSession = $customerSession->create();
            parent::__construct($context);
    }



    public function getShipping() {
        //get customer model before you can get its address data

        if($this->customerSession->isLoggedIn()) { 
         $shippingAddressId=$this->customerSession->getCustomer()->getDefaultShipping();
         $shippingAddress = $this->_addressFactory->create()->load($shippingAddressId);
         $shippingdata= $shippingAddress->getData();

         return $shippingdata;
        }
        else
        {
            return '';
        }
     }
}

You can call it in Template(.phtml) file as below:

$shippingblock=$block->getLayout()->createBlock('Vendor\Module\Block\Shipping');
$shippingAddress=$shippingblock->getShipping();
  • In order to populate this xml layout files,do we need to write a js as intermediate step?or directly can we populate this data to xml item attributes? – sahana Feb 19 at 8:40
  • No need to write js. You can simply call this block method in any template file(.phtml) file. – Khushbu Feb 19 at 8:42
  • I have updated my answer. Please check. – Khushbu Feb 19 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.