Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Save.php
Go to the documentation of this file.
1 <?php
7 
8 use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
16 
21 {
25  private $emailNotification;
26 
32  protected function _extractCustomerData()
33  {
34  $customerData = [];
35  if ($this->getRequest()->getPost('customer')) {
36  $additionalAttributes = [
39  'confirmation',
40  'sendemail_store_id',
41  'extension_attributes',
42  ];
43 
44  $customerData = $this->_extractData(
45  'adminhtml_customer',
46  CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER,
47  $additionalAttributes,
48  'customer'
49  );
50  }
51 
52  if (isset($customerData['disable_auto_group_change'])) {
53  $customerData['disable_auto_group_change'] = (int) filter_var(
54  $customerData['disable_auto_group_change'],
55  FILTER_VALIDATE_BOOLEAN
56  );
57  }
58 
59  return $customerData;
60  }
61 
71  protected function _extractData(
72  $formCode,
74  $additionalAttributes = [],
75  $scope = null
76  ) {
77  $metadataForm = $this->getMetadataForm($entityType, $formCode, $scope);
78  $formData = $metadataForm->extractData($this->getRequest(), $scope);
79  $formData = $metadataForm->compactData($formData);
80 
81  // Initialize additional attributes
83  $object = $this->_objectFactory->create(['data' => $this->getRequest()->getPostValue()]);
84  $requestData = $object->getData($scope);
85  foreach ($additionalAttributes as $attributeCode) {
87  }
88 
89  // Unset unused attributes
90  $formAttributes = $metadataForm->getAttributes();
91  foreach ($formAttributes as $attribute) {
93  $attributeCode = $attribute->getAttributeCode();
94  if ($attribute->getFrontendInput() != 'boolean'
95  && $formData[$attributeCode] === false
96  ) {
97  unset($formData[$attributeCode]);
98  }
99  }
100 
101  if (empty($formData['extension_attributes'])) {
102  unset($formData['extension_attributes']);
103  }
104 
105  return $formData;
106  }
107 
115  protected function saveDefaultFlags(array $addressIdList, array & $extractedCustomerData)
116  {
117  $result = [];
118  $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = null;
119  $extractedCustomerData[CustomerInterface::DEFAULT_SHIPPING] = null;
120  foreach ($addressIdList as $addressId) {
121  $scope = sprintf('address/%s', $addressId);
122  $addressData = $this->_extractData(
123  'adminhtml_customer_address',
124  AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
125  ['default_billing', 'default_shipping'],
126  $scope
127  );
128 
129  if (is_numeric($addressId)) {
130  $addressData['id'] = $addressId;
131  }
132  // Set default billing and shipping flags to customer
133  if (!empty($addressData['default_billing']) && $addressData['default_billing'] === 'true') {
134  $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = $addressId;
135  $addressData['default_billing'] = true;
136  } else {
137  $addressData['default_billing'] = false;
138  }
139  if (!empty($addressData['default_shipping']) && $addressData['default_shipping'] === 'true') {
140  $extractedCustomerData[CustomerInterface::DEFAULT_SHIPPING] = $addressId;
141  $addressData['default_shipping'] = true;
142  } else {
143  $addressData['default_shipping'] = false;
144  }
145  $result[] = $addressData;
146  }
147  return $result;
148  }
149 
156  protected function _extractCustomerAddressData(array & $extractedCustomerData)
157  {
158  $addresses = $this->getRequest()->getPost('address');
159  $result = [];
160  if (is_array($addresses)) {
161  if (isset($addresses['_template_'])) {
162  unset($addresses['_template_']);
163  }
164 
165  $addressIdList = array_keys($addresses);
166  $result = $this->saveDefaultFlags($addressIdList, $extractedCustomerData);
167  }
168 
169  return $result;
170  }
171 
180  public function execute()
181  {
182  $returnToEdit = false;
183  $originalRequestData = $this->getRequest()->getPostValue();
184 
185  $customerId = $this->getCurrentCustomerId();
186 
187  if ($originalRequestData) {
188  try {
189  // optional fields might be set in request for future processing by observers in other modules
191  $addressesData = $this->_extractCustomerAddressData($customerData);
192 
193  if ($customerId) {
194  $currentCustomer = $this->_customerRepository->getById($customerId);
195  $customerData = array_merge(
196  $this->customerMapper->toFlatArray($currentCustomer),
198  );
199  $customerData['id'] = $customerId;
200  }
201 
203  $customer = $this->customerDataFactory->create();
204  $this->dataObjectHelper->populateWithArray(
205  $customer,
207  \Magento\Customer\Api\Data\CustomerInterface::class
208  );
209  $addresses = [];
210  foreach ($addressesData as $addressData) {
211  $region = isset($addressData['region']) ? $addressData['region'] : null;
212  $regionId = isset($addressData['region_id']) ? $addressData['region_id'] : null;
213  $addressData['region'] = [
214  'region' => $region,
215  'region_id' => $regionId,
216  ];
217  $addressDataObject = $this->addressDataFactory->create();
218  $this->dataObjectHelper->populateWithArray(
219  $addressDataObject,
220  $addressData,
221  \Magento\Customer\Api\Data\AddressInterface::class
222  );
223  $addresses[] = $addressDataObject;
224  }
225 
226  $this->_eventManager->dispatch(
227  'adminhtml_customer_prepare_save',
228  ['customer' => $customer, 'request' => $this->getRequest()]
229  );
230  $customer->setAddresses($addresses);
231  if (isset($customerData['sendemail_store_id'])) {
232  $customer->setStoreId($customerData['sendemail_store_id']);
233  }
234 
235  // Save customer
236  if ($customerId) {
237  $this->_customerRepository->save($customer);
238 
239  $this->getEmailNotification()->credentialsChanged($customer, $currentCustomer->getEmail());
240  } else {
241  $customer = $this->customerAccountManagement->createAccount($customer);
242  $customerId = $customer->getId();
243  }
244 
245  $isSubscribed = null;
246  if ($this->_authorization->isAllowed(null)) {
247  $isSubscribed = $this->getRequest()->getPost('subscription');
248  }
249  if ($isSubscribed !== null) {
250  if ($isSubscribed !== '0') {
251  $this->_subscriberFactory->create()->subscribeCustomerById($customerId);
252  } else {
253  $this->_subscriberFactory->create()->unsubscribeCustomerById($customerId);
254  }
255  }
256 
257  // After save
258  $this->_eventManager->dispatch(
259  'adminhtml_customer_save_after',
260  ['customer' => $customer, 'request' => $this->getRequest()]
261  );
262  $this->_getSession()->unsCustomerFormData();
263  // Done Saving customer, finish save action
264  $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId);
265  $this->messageManager->addSuccess(__('You saved the customer.'));
266  $returnToEdit = (bool)$this->getRequest()->getParam('back', false);
267  } catch (\Magento\Framework\Validator\Exception $exception) {
268  $messages = $exception->getMessages();
269  if (empty($messages)) {
270  $messages = $exception->getMessage();
271  }
272  $this->_addSessionErrorMessages($messages);
273  $this->_getSession()->setCustomerFormData($originalRequestData);
274  $returnToEdit = true;
275  } catch (\Magento\Framework\Exception\AbstractAggregateException $exception) {
276  $errors = $exception->getErrors();
277  $messages = [];
278  foreach ($errors as $error) {
279  $messages[] = $error->getMessage();
280  }
281  $this->_addSessionErrorMessages($messages);
282  $this->_getSession()->setCustomerFormData($originalRequestData);
283  $returnToEdit = true;
284  } catch (LocalizedException $exception) {
285  $this->_addSessionErrorMessages($exception->getMessage());
286  $this->_getSession()->setCustomerFormData($originalRequestData);
287  $returnToEdit = true;
288  } catch (\Exception $exception) {
289  $this->messageManager->addException($exception, __('Something went wrong while saving the customer.'));
290  $this->_getSession()->setCustomerFormData($originalRequestData);
291  $returnToEdit = true;
292  }
293  }
294  $resultRedirect = $this->resultRedirectFactory->create();
295  if ($returnToEdit) {
296  if ($customerId) {
297  $resultRedirect->setPath(
298  'customer/*/edit',
299  ['id' => $customerId, '_current' => true]
300  );
301  } else {
302  $resultRedirect->setPath(
303  'customer/*/new',
304  ['_current' => true]
305  );
306  }
307  } else {
308  $resultRedirect->setPath('customer/index');
309  }
310  return $resultRedirect;
311  }
312 
319  private function getEmailNotification()
320  {
321  if (!($this->emailNotification instanceof EmailNotificationInterface)) {
322  return \Magento\Framework\App\ObjectManager::getInstance()->get(
323  EmailNotificationInterface::class
324  );
325  } else {
326  return $this->emailNotification;
327  }
328  }
329 
338  private function getMetadataForm($entityType, $formCode, $scope)
339  {
340  $attributeValues = [];
341 
342  if ($entityType == CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER) {
343  $customerId = $this->getCurrentCustomerId();
344  if ($customerId) {
345  $customer = $this->_customerRepository->getById($customerId);
346  $attributeValues = $this->customerMapper->toFlatArray($customer);
347  }
348  }
349 
350  if ($entityType == AddressMetadataInterface::ENTITY_TYPE_ADDRESS) {
351  $scopeData = explode('/', $scope);
352  if (isset($scopeData[1]) && is_numeric($scopeData[1])) {
353  $customerAddress = $this->addressRepository->getById($scopeData[1]);
354  $attributeValues = $this->addressMapper->toFlatArray($customerAddress);
355  }
356  }
357 
358  $metadataForm = $this->_formFactory->create(
359  $entityType,
360  $formCode,
362  false,
363  Form::DONT_IGNORE_INVISIBLE
364  );
365 
366  return $metadataForm;
367  }
368 
374  private function getCurrentCustomerId()
375  {
376  $originalRequestData = $this->getRequest()->getPostValue(CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER);
377 
378  $customerId = isset($originalRequestData['entity_id'])
379  ? $originalRequestData['entity_id']
380  : null;
381 
382  return $customerId;
383  }
384 }
$customerData
$customer
Definition: customers.php:11
return false
Definition: gallery.phtml:36
$addresses
Definition: address_list.php:7
__()
Definition: __.php:13
saveDefaultFlags(array $addressIdList, array & $extractedCustomerData)
Definition: Save.php:115
$addressData
Definition: order.php:19
$attributeCode
Definition: extend.phtml:12
_extractCustomerAddressData(array & $extractedCustomerData)
Definition: Save.php:156
$errors
Definition: overview.phtml:9
$customerAddress