1

From customer registration page i'm getting address entered by customer. I want to save this address twice in customer address table one for default shipping and one default billing. I'm extending creatPost controller and trying to modify extractAddress function.

I did this but not working as expected

protected function extractAddress()
{
    if (!$this->getRequest()->getPost('create_address')) {
        return null;
    }

    $addressForm = $this->formFactory->create('customer_address', 'customer_register_address');
    $allowedAttributes = $addressForm->getAllowedAttributes();

    $addressData = [];

    $regionDataObject = $this->regionDataFactory->create();
    foreach ($allowedAttributes as $attribute) {
        $attributeCode = $attribute->getAttributeCode();
        $value = $this->getRequest()->getParam($attributeCode);
        if ($value === null) {
            continue;
        }
        switch ($attributeCode) {
            case 'region_id':
                $regionDataObject->setRegionId($value);
                break;
            case 'region':
                $regionDataObject->setRegion($value);
                break;
            default:
                $addressData[$attributeCode] = $value;
        }
    }
    $arr = [];
    $arr[] = $addressData;
    $arr[] = $addressData;
    for($i=0;$i<2;$i++){
        $addressDataObject = $this->addressDataFactory->create();
        $this->dataObjectHelper->populateWithArray(
            $addressDataObject,
            $arr[$i],
            \Magento\Customer\Api\Data\AddressInterface::class
        );
        $addressDataObject->setRegion($regionDataObject);
        if ($i==0){
            $addressDataObject->setIsDefaultBilling(
                $this->getRequest()->getParam('default_billing', false)
                );
            } else {
            $addressDataObject->setIsDefaultShipping(
                $this->getRequest()->getParam('default_shipping', false)
            );
        }
    }
    return $addressDataObject;
}

public function execute()
{
     $resultRedirect = $this->resultRedirectFactory->create();
     $this->session->regenerateId();
     try {
        $address = $this->extractAddress();
        $addresses = $address === null ? [] : [$address];

        $customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
        $customer->setAddresses($addresses);
    }
}
live2
  • 3,771
  • 2
  • 37
  • 46
ravichandra
  • 111
  • 3

0 Answers0