Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
FormPost.php
Go to the documentation of this file.
1 <?php
8 
9 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
11 use Magento\Customer\Api\Data\AddressInterfaceFactory;
13 use Magento\Customer\Api\Data\RegionInterfaceFactory;
17 use Magento\Directory\Helper\Data as HelperData;
22 use Magento\Framework\Controller\Result\ForwardFactory;
23 use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
27 
32 {
36  protected $regionFactory;
37 
41  protected $helperData;
42 
46  private $customerAddressMapper;
47 
64  public function __construct(
65  Context $context,
66  Session $customerSession,
67  FormKeyValidator $formKeyValidator,
68  FormFactory $formFactory,
70  AddressInterfaceFactory $addressDataFactory,
71  RegionInterfaceFactory $regionDataFactory,
72  DataObjectProcessor $dataProcessor,
74  ForwardFactory $resultForwardFactory,
77  HelperData $helperData
78  ) {
79  $this->regionFactory = $regionFactory;
80  $this->helperData = $helperData;
81  parent::__construct(
82  $context,
83  $customerSession,
84  $formKeyValidator,
85  $formFactory,
89  $dataProcessor,
93  );
94  }
95 
101  protected function _extractAddress()
102  {
103  $existingAddressData = $this->getExistingAddressData();
104 
106  $addressForm = $this->_formFactory->create(
107  'customer_address',
108  'customer_address_edit',
109  $existingAddressData
110  );
111  $addressData = $addressForm->extractData($this->getRequest());
112  $attributeValues = $addressForm->compactData($addressData);
113 
115 
116  $addressDataObject = $this->addressDataFactory->create();
117  $this->dataObjectHelper->populateWithArray(
118  $addressDataObject,
119  array_merge($existingAddressData, $attributeValues),
120  \Magento\Customer\Api\Data\AddressInterface::class
121  );
122  $addressDataObject->setCustomerId($this->_getSession()->getCustomerId())
123  ->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
124  ->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
125 
126  return $addressDataObject;
127  }
128 
135  protected function getExistingAddressData()
136  {
137  $existingAddressData = [];
138  if ($addressId = $this->getRequest()->getParam('id')) {
139  $existingAddress = $this->_addressRepository->getById($addressId);
140  if ($existingAddress->getCustomerId() !== $this->_getSession()->getCustomerId()) {
141  throw new \Exception();
142  }
143  $existingAddressData = $this->getCustomerAddressMapper()->toFlatArray($existingAddress);
144  }
145  return $existingAddressData;
146  }
147 
155  protected function updateRegionData(&$attributeValues)
156  {
157  if (!empty($attributeValues['region_id'])) {
158  $newRegion = $this->regionFactory->create()->load($attributeValues['region_id']);
159  $attributeValues['region_code'] = $newRegion->getCode();
160  $attributeValues['region'] = $newRegion->getDefaultName();
161  }
162 
163  $regionData = [
164  RegionInterface::REGION_ID => !empty($attributeValues['region_id']) ? $attributeValues['region_id'] : null,
165  RegionInterface::REGION => !empty($attributeValues['region']) ? $attributeValues['region'] : null,
166  RegionInterface::REGION_CODE => !empty($attributeValues['region_code'])
167  ? $attributeValues['region_code']
168  : null,
169  ];
170 
171  $region = $this->regionDataFactory->create();
172  $this->dataObjectHelper->populateWithArray(
173  $region,
174  $regionData,
175  \Magento\Customer\Api\Data\RegionInterface::class
176  );
177  $attributeValues['region'] = $region;
178  }
179 
185  public function execute()
186  {
187  $redirectUrl = null;
188  if (!$this->_formKeyValidator->validate($this->getRequest())) {
189  return $this->resultRedirectFactory->create()->setPath('*/*/');
190  }
191 
192  if (!$this->getRequest()->isPost()) {
193  $this->_getSession()->setAddressFormData($this->getRequest()->getPostValue());
194  return $this->resultRedirectFactory->create()->setUrl(
195  $this->_redirect->error($this->_buildUrl('*/*/edit'))
196  );
197  }
198 
199  try {
200  $address = $this->_extractAddress();
201  $this->_addressRepository->save($address);
202  $this->messageManager->addSuccessMessage(__('You saved the address.'));
203  $url = $this->_buildUrl('*/*/index', ['_secure' => true]);
204  return $this->resultRedirectFactory->create()->setUrl($this->_redirect->success($url));
205  } catch (InputException $e) {
206  $this->messageManager->addErrorMessage($e->getMessage());
207  foreach ($e->getErrors() as $error) {
208  $this->messageManager->addErrorMessage($error->getMessage());
209  }
210  } catch (\Exception $e) {
211  $redirectUrl = $this->_buildUrl('*/*/index');
212  $this->messageManager->addExceptionMessage($e, __('We can\'t save the address.'));
213  }
214 
215  $url = $redirectUrl;
216  if (!$redirectUrl) {
217  $this->_getSession()->setAddressFormData($this->getRequest()->getPostValue());
218  $url = $this->_buildUrl('*/*/edit', ['id' => $this->getRequest()->getParam('id')]);
219  }
220 
221  return $this->resultRedirectFactory->create()->setUrl($this->_redirect->error($url));
222  }
223 
231  private function getCustomerAddressMapper()
232  {
233  if ($this->customerAddressMapper === null) {
234  $this->customerAddressMapper = ObjectManager::getInstance()->get(
235  \Magento\Customer\Model\Address\Mapper::class
236  );
237  }
238  return $this->customerAddressMapper;
239  }
240 }
$regionFactory
Definition: FormPost.php:36
$addressRepository
_redirect($path, $arguments=[])
Definition: Action.php:167
updateRegionData(&$attributeValues)
Definition: FormPost.php:155
__()
Definition: __.php:13
$address
Definition: customer.php:38
$addressData
Definition: order.php:19
getExistingAddressData()
Definition: FormPost.php:135
execute()
Definition: FormPost.php:185
Definition: FormPost.php:31
$helperData
Definition: FormPost.php:41
__construct(Context $context, Session $customerSession, FormKeyValidator $formKeyValidator, FormFactory $formFactory, AddressRepositoryInterface $addressRepository, AddressInterfaceFactory $addressDataFactory, RegionInterfaceFactory $regionDataFactory, DataObjectProcessor $dataProcessor, DataObjectHelper $dataObjectHelper, ForwardFactory $resultForwardFactory, PageFactory $resultPageFactory, RegionFactory $regionFactory, HelperData $helperData)
Definition: FormPost.php:64