Set Phone Number in Checkout Page – Magento 2 Guide

checkoutmagento2

In my module i am creating one customer attribute in that i saved customer phone number.

Now i want to set that number in phone number field on checkout page if there is no address saved.

is this possible to do? if yes than how can i do this?

EDIT

InstallData

$customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);
        $customerEntity = $customerSetup->getEavConfig()->getEntityType('customer');
        $attributeSetId = $customerEntity->getDefaultAttributeSetId();

  $attributeSet = $this->attributeSetFactory->create();
        $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

        $customerSetup->addAttribute(\Magento\Customer\Model\Customer::ENTITY, 'telephone_no', [
            'type' => 'varchar',
            'label' => 'Telephone No.',
            'input' => 'text',
            'required' => false,
            'visible' => true,
            'user_defined' => true,
            'sort_order' => 90,
            'position' => 90,
            'system' => 0,
        ]);

        $attribute = $customerSetup->getEavConfig()->getAttribute(\Magento\Customer\Model\Customer::ENTITY, 'telephone_no')
            ->addData([
                'attribute_set_id' => $attributeSetId,
                'attribute_group_id' => $attributeGroupId,
                'used_in_forms' => ['adminhtml_customer'],
            ]);

        $attribute->save();

EDIT THIS ONLY

 'used_in_forms' => ['adminhtml_customer','checkout_register','customer_account_create','customer_account_edit','adminhtml_checkout']

Best Answer

Yes,it possible

At class of Magento\Checkout\Block\Checkout\AttributeMerger in function getDefaultValue($attributeCode) ,

and below code:

case 'telephone':
                /* add by Amit Bera */
                if ($this->getCustomer()) {
                    return $this->getCustomer()->getYourCustomfield();
                }
                break;

Edited:

You done the mistake,you need to assign that field checkout and other form where you need it

 $used_in_forms[]="adminhtml_customer";
        $used_in_forms[]="checkout_register";
        $used_in_forms[]="customer_account_create";
        $used_in_forms[]="customer_account_edit";
        $used_in_forms[]="adminhtml_checkout";
        $attribute->setData("used_in_forms", $used_in_forms)
            ->setData("is_used_for_customer_segment", true)
            ->setData("is_system", 0)
            ->setData("is_user_defined", 1)
            ->setData("is_visible", 1)
            ->setData("sort_order", 100);

        $attribute->save();
Related Topic