/** * Make sure customer is valid, if logged in * * By default will add error messages and redirect to customer edit form * * @param bool $redirect - stop dispatch and redirect? * @param bool $addErrors - add error messages? * @return bool */ protected function _preDispatchValidateCustomer($redirect = true, $addErrors = true) { try { $customerId = $this->_customerSession->getCustomerId(); $customer = $this->_customerAccountService->getCustomer($customerId); } catch (NoSuchEntityException $e) { return true; } if (isset($customer)) { $validationResult = $this->_customerAccountService->validateCustomerData($customer, $this->_customerMetadataService->getAllCustomerAttributeMetadata()); if (!$validationResult->isValid()) { if ($addErrors) { foreach ($validationResult->getMessages() as $error) { $this->messageManager->addError($error); } } if ($redirect) { $this->_redirect('customer/account/edit'); $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); } return false; } } return true; }
public function setUp() { $this->context = $this->getMockBuilder('Magento\\Framework\\App\\Helper\\Context')->disableOriginalConstructor()->getMock(); $this->customerMetadataService = $this->getMockBuilder('Magento\\Customer\\Service\\V1\\CustomerMetadataServiceInterface')->disableOriginalConstructor()->getMock(); $attributeMetadata = $this->getMockBuilder('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata')->disableOriginalConstructor()->getMock(); $attributeMetadata->expects($this->any())->method('isVisible')->will($this->returnValue(true)); $this->customerMetadataService->expects($this->any())->method('getAttributeMetadata')->will($this->returnValue($attributeMetadata)); $this->object = new View($this->context, $this->customerMetadataService); }
/** * @param \Magento\Customer\Service\V1\Data\Customer $customerData * @param string $expectedCustomerName * @param bool $isPrefixAllowed * @param bool $isMiddleNameAllowed * @param bool $isSuffixAllowed * @dataProvider getCustomerNameDataProvider */ public function testGetCustomerName($customerData, $expectedCustomerName, $isPrefixAllowed = false, $isMiddleNameAllowed = false, $isSuffixAllowed = false) { $visibleAttribute = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata', array(), array(), '', false); $visibleAttribute->expects($this->any())->method('isVisible')->will($this->returnValue(true)); $invisibleAttribute = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata', array(), array(), '', false); $invisibleAttribute->expects($this->any())->method('isVisible')->will($this->returnValue(false)); $this->_customerMetadataService->expects($this->any())->method('getAttributeMetadata')->will($this->returnValueMap(array(array('customer', 'prefix', $isPrefixAllowed ? $visibleAttribute : $invisibleAttribute), array('customer', 'middlename', $isMiddleNameAllowed ? $visibleAttribute : $invisibleAttribute), array('customer', 'suffix', $isSuffixAllowed ? $visibleAttribute : $invisibleAttribute)))); $this->assertEquals($expectedCustomerName, $this->_helper->getCustomerName($customerData), 'Full customer name is invalid'); }
/** * @param \Magento\Sales\Model\Quote\Address $address * @return \Magento\Checkout\Service\V1\Data\Cart\Address */ public function convertModelToDataObject(\Magento\Sales\Model\Quote\Address $address) { $data = [Address::KEY_COUNTRY_ID => $address->getCountryId(), Address::KEY_ID => $address->getId(), Address::KEY_CUSTOMER_ID => $address->getCustomerId(), Address::KEY_REGION => array(Region::KEY_REGION => $address->getRegion(), Region::KEY_REGION_ID => $address->getRegionId(), Region::KEY_REGION_CODE => $address->getRegionCode()), Address::KEY_STREET => $address->getStreet(), Address::KEY_COMPANY => $address->getCompany(), Address::KEY_TELEPHONE => $address->getTelephone(), Address::KEY_FAX => $address->getFax(), Address::KEY_POSTCODE => $address->getPostcode(), Address::KEY_CITY => $address->getCity(), Address::KEY_FIRSTNAME => $address->getFirstname(), Address::KEY_LASTNAME => $address->getLastname(), Address::KEY_MIDDLENAME => $address->getMiddlename(), Address::KEY_PREFIX => $address->getPrefix(), Address::KEY_SUFFIX => $address->getSuffix(), Address::KEY_EMAIL => $address->getEmail(), Address::KEY_VAT_ID => $address->getVatId()]; foreach ($this->metadataService->getCustomAttributesMetadata() as $attributeMetadata) { $attributeCode = $attributeMetadata->getAttributeCode(); $method = 'get' . SimpleDataObjectConverter::snakeCaseToCamelCase($attributeCode); $data[Address::CUSTOM_ATTRIBUTES_KEY][] = [AttributeValue::ATTRIBUTE_CODE => $attributeCode, AttributeValue::VALUE => $address->{$method}()]; } return $this->addressBuilder->populateWithArray($data)->create(); }
public function testGetAttributeMetadataWithoutAttributeMetadata() { $this->attributeMetadataDataProvider->expects($this->any())->method('getAttribute')->will($this->returnValue(false)); try { $this->service->getAttributeMetadata('attributeId'); $this->fail('Expected exception not thrown.'); } catch (NoSuchEntityException $e) { $this->assertSame("No such entity with entityType = customer, attributeCode = attributeId", $e->getMessage()); } }
/** * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function testCreateAddressFromModelWithCustomerId() { $defaultBillingId = 1; $defaultShippingId = 1; $customerId = 1; $attributeCode = 'attribute_code'; $addressModelMock = $this->getAddressMockForCreate(); $addressModelMock->expects($this->once())->method('getId')->will($this->returnValue(null)); $addressModelMock->expects($this->any())->method('getCustomerId')->will($this->returnValue($customerId)); $addressModelMock->expects($this->any())->method('getParentId'); $getData = function ($key, $index = null) use($attributeCode, $customerId) { $result = null; switch ($key) { case $attributeCode: $result = 'some_data'; break; case 'customer_id': $result = $customerId; break; } return $result; }; $addressModelMock->expects($this->any())->method('getData')->will($this->returnCallback($getData)); $attributeMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata', array('getAttributeCode'), array(), '', false); $attributeMock->expects($this->once())->method('getAttributeCode')->will($this->returnValue($attributeCode)); $addressMock = $this->getMock('Magento\\Customer\\Service\\V1\\Data\\Address', array(), array(), '', false); $this->metadataServiceMock->expects($this->once())->method('getAllAddressAttributeMetadata')->will($this->returnValue(array($attributeMock))); $this->addressBuilderMock->expects($this->once())->method('create')->will($this->returnValue($addressMock)); $this->addressBuilderMock->expects($this->once())->method('setCustomerId')->with($this->equalTo($customerId)); $this->assertEquals($addressMock, $this->model->createAddressFromModel($addressModelMock, $defaultBillingId, $defaultShippingId)); }
/** * Edit/View Existing Customer form fields * * @param \Magento\Framework\Data\Form\Element\Fieldset $fieldset * @return string[] Values to set on the form */ protected function _addEditCustomerFormFields($fieldset) { $fieldset->getForm()->getElement('created_in')->setDisabled('disabled'); $fieldset->getForm()->getElement('website_id')->setDisabled('disabled'); $customerData = $this->_getCustomerDataObject(); if ($customerData->getId() && !$this->_customerAccountService->canModify($customerData->getId())) { return array(); } // Prepare customer confirmation control (only for existing customers) $confirmationStatus = $this->_customerAccountService->getConfirmationStatus($customerData->getId()); $confirmationKey = $customerData->getConfirmation(); if ($confirmationStatus != CustomerAccountServiceInterface::ACCOUNT_CONFIRMED) { $confirmationAttr = $this->_customerMetadataService->getCustomerAttributeMetadata('confirmation'); if (!$confirmationKey) { $confirmationKey = $this->_getRandomConfirmationKey(); } $element = $fieldset->addField('confirmation', 'select', array('name' => 'confirmation', 'label' => __($confirmationAttr->getFrontendLabel()))); $element->setEntityAttribute($confirmationAttr); $element->setValues(array('' => 'Confirmed', $confirmationKey => 'Not confirmed')); // Prepare send welcome email checkbox if customer is not confirmed // no need to add it, if website ID is empty if ($customerData->getConfirmation() && $customerData->getWebsiteId()) { $fieldset->addField('sendemail', 'checkbox', array('name' => 'sendemail', 'label' => __('Send Welcome Email after Confirmation'))); return array('sendemail' => '1'); } } return array(); }
/** * Retrieve attributes metadata for the form * * @return \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata[] */ public function getAttributes() { if (!isset($this->_attributes)) { $this->_attributes = $this->_eavMetadataService->getAttributes($this->_entityType, $this->_formCode); } return $this->_attributes; }
/** * {@inheritdoc} */ public function getCustomAttributesCodes() { $attributeCodes = array(); foreach ($this->_metadataService->getCustomAddressAttributeMetadata() as $attribute) { $attributeCodes[] = $attribute->getAttributeCode(); } return $attributeCodes; }
/** * Retrieve customer attribute instance * * @param string $attributeCode * @return \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata|null */ protected function _getAttribute($attributeCode) { try { return $this->customerMetadataService->getAttributeMetadata($attributeCode); } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { return null; } }
public function testGetAddressAttributeMetadataNoSuchEntity() { try { $this->_service->getAddressAttributeMetadata('1'); $this->fail('Expected exception not thrown.'); } catch (NoSuchEntityException $e) { $this->assertEquals('No such entity with entityType = customer_address, attributeCode = 1', $e->getMessage()); } }
/** * Concatenate all customer name parts into full customer name. * * @param \Magento\Customer\Service\V1\Data\Customer $customerData * @return string */ public function getCustomerName(\Magento\Customer\Service\V1\Data\Customer $customerData) { $name = ''; $prefixMetadata = $this->_customerMetadataService->getAttributeMetadata('customer', 'prefix'); if ($prefixMetadata->isVisible() && $customerData->getPrefix()) { $name .= $customerData->getPrefix() . ' '; } $name .= $customerData->getFirstname(); $middleNameMetadata = $this->_customerMetadataService->getAttributeMetadata('customer', 'middlename'); if ($middleNameMetadata->isVisible() && $customerData->getMiddlename()) { $name .= ' ' . $customerData->getMiddlename(); } $name .= ' ' . $customerData->getLastname(); $suffixMetadata = $this->_customerMetadataService->getAttributeMetadata('customer', 'suffix'); if ($suffixMetadata->isVisible() && $customerData->getSuffix()) { $name .= ' ' . $customerData->getSuffix(); } return $name; }
/** * @param $attrCode * @param $attrClass * @param $customAttrClass * @param $result * @dataProvider getAttributeValidationClassDataProvider */ public function testGetAttributeValidationClass($attrCode, $attrClass, $customAttrClass, $result) { $attributeMock = $this->getMockBuilder('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata')->disableOriginalConstructor()->getMock(); $attributeMock->expects($this->any())->method('getFrontendClass')->will($this->returnValue($attrClass)); $customAttrMock = $this->getMockBuilder('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata')->disableOriginalConstructor()->getMock(); $customAttrMock->expects($this->any())->method('isVisible')->will($this->returnValue(true)); $customAttrMock->expects($this->any())->method('getFrontendClass')->will($this->returnValue($customAttrClass)); $this->customerMetadataService->expects($this->any())->method('getAttributeMetadata')->will($this->returnValueMap(array(array('customer_address', $attrCode, $attributeMock), array('customer', $attrCode, $customAttrMock)))); $this->assertEquals($result, $this->helper->getAttributeValidationClass($attrCode)); }
public function testGetAttributes() { $formAttributesMetadata = $this->_service->getAttributes('adminhtml_customer'); $this->assertCount(14, $formAttributesMetadata, "Invalid number of attributes for the specified form."); /** Check some fields of one attribute metadata */ $attributeMetadata = $formAttributesMetadata['firstname']; $this->assertInstanceOf('Magento\\Customer\\Service\\V1\\Data\\Eav\\AttributeMetadata', $attributeMetadata); $this->assertEquals('firstname', $attributeMetadata->getAttributeCode(), 'Attribute code is invalid'); $this->assertNotEmpty($attributeMetadata->getValidationRules(), 'Validation rules are not set'); $this->assertEquals('1', $attributeMetadata->isSystem(), '"Is system" field value is invalid'); $this->assertEquals('40', $attributeMetadata->getSortOrder(), 'Sort order is invalid'); }
/** * {@inheritdoc} * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function renderArray($addressAttributes, $format = null) { switch ($this->getType()->getCode()) { case 'html': $dataFormat = ElementFactory::OUTPUT_FORMAT_HTML; break; case 'pdf': $dataFormat = ElementFactory::OUTPUT_FORMAT_PDF; break; case 'oneline': $dataFormat = ElementFactory::OUTPUT_FORMAT_ONELINE; break; default: $dataFormat = ElementFactory::OUTPUT_FORMAT_TEXT; break; } $attributesMetadata = $this->_metadataService->getAllAddressAttributeMetadata(); $data = array(); foreach ($attributesMetadata as $attributeMetadata) { if (!$attributeMetadata->isVisible()) { continue; } $attributeCode = $attributeMetadata->getAttributeCode(); if ($attributeCode == 'country_id' && isset($addressAttributes['country_id'])) { $data['country'] = $this->_countryFactory->create()->loadByCode($addressAttributes['country_id'])->getName(); } elseif ($attributeCode == 'region' && isset($addressAttributes['region'])) { $data['region'] = __($addressAttributes['region']); } elseif (isset($addressAttributes[$attributeCode])) { $value = $addressAttributes[$attributeCode]; $dataModel = $this->_elementFactory->create($attributeMetadata, $value, 'customer_address'); $value = $dataModel->outputValue($dataFormat); if ($attributeMetadata->getFrontendInput() == 'multiline') { $values = $dataModel->outputValue(ElementFactory::OUTPUT_FORMAT_ARRAY); // explode lines foreach ($values as $k => $v) { $key = sprintf('%s%d', $attributeCode, $k + 1); $data[$key] = $v; } } $data[$attributeCode] = $value; } } if ($this->getType()->getEscapeHtml()) { foreach ($data as $key => $value) { $data[$key] = $this->escapeHtml($value); } } $format = !is_null($format) ? $format : $this->getFormatArray($addressAttributes); return $this->filterManager->template($format, array('variables' => $data)); }
/** * Retrieve attributes metadata for the form * * @return \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata[] * @throws \LogicException For undefined entity type */ public function getAttributes() { if (!isset($this->_attributes)) { if ($this->_entityType === CustomerMetadataServiceInterface::ENTITY_TYPE_CUSTOMER) { $this->_attributes = $this->_customerMetadataService->getAttributes($this->_formCode); } else { if ($this->_entityType === AddressMetadataServiceInterface::ENTITY_TYPE_ADDRESS) { $this->_attributes = $this->_addressMetadataService->getAttributes($this->_formCode); } else { throw new \LogicException('Undefined entity type: ' . $this->_entityType); } } } return $this->_attributes; }
/** * Get string with frontend validation classes for attribute * * @param string $attributeCode * @return string * * @SuppressWarnings(PHPMD.NPathComplexity) */ public function getAttributeValidationClass($attributeCode) { /** @var $attribute \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata */ $attribute = isset($this->_attributes[$attributeCode]) ? $this->_attributes[$attributeCode] : $this->_customerMetadataService->getAttributeMetadata('customer_address', $attributeCode); $class = $attribute ? $attribute->getFrontendClass() : ''; if (in_array($attributeCode, array('firstname', 'middlename', 'lastname', 'prefix', 'suffix', 'taxvat'))) { if ($class && !$attribute->isVisible()) { // address attribute is not visible thus its validation rules are not applied $class = ''; } /** @var $customerAttribute \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata */ $customerAttribute = $this->_customerMetadataService->getAttributeMetadata('customer', $attributeCode); $class .= $customerAttribute && $customerAttribute->isVisible() ? $customerAttribute->getFrontendClass() : ''; $class = implode(' ', array_unique(array_filter(explode(' ', $class)))); } return $class; }
/** * Return array of additional account data * Value is option style array * * @return array */ public function getCustomerAccountData() { $accountData = array(); $entityType = 'customer'; foreach ($this->_customerMetadataService->getAllAttributesMetadata($entityType) as $attribute) { /* @var $attribute \Magento\Customer\Service\V1\Data\Eav\AttributeMetadata */ if (!$attribute->isVisible() || $attribute->isSystem()) { continue; } $orderKey = sprintf('customer_%s', $attribute->getAttributeCode()); $orderValue = $this->getOrder()->getData($orderKey); if ($orderValue != '') { $metadataElement = $this->_metadataElementFactory->create($attribute, $orderValue, $entityType); $value = $metadataElement->outputValue(AttributeDataFactory::OUTPUT_FORMAT_HTML); $sortOrder = $attribute->getSortOrder() + $attribute->isUserDefined() ? 200 : 0; $sortOrder = $this->_prepareAccountDataSortOrder($accountData, $sortOrder); $accountData[$sortOrder] = array('label' => $attribute->getFrontendLabel(), 'value' => $this->escapeHtml($value, array('br'))); } } ksort($accountData, SORT_NUMERIC); return $accountData; }
/** * Make address Data Object out of an address model * * @param AbstractAddress $addressModel * @param int $defaultBillingId * @param int $defaultShippingId * @return Address */ public function createAddressFromModel(AbstractAddress $addressModel, $defaultBillingId, $defaultShippingId) { $addressId = $addressModel->getId(); $attributes = $this->_metadataService->getAllAddressAttributeMetadata(); $addressData = array(); foreach ($attributes as $attribute) { $code = $attribute->getAttributeCode(); if (!is_null($addressModel->getData($code))) { $addressData[$code] = $addressModel->getData($code); } } $isDefaultBilling = $addressModel->getData('is_default_billing') === null && intval($addressId) ? $addressId === $defaultBillingId : $addressModel->getData('is_default_billing'); $isDefaultShipping = $addressModel->getData('is_default_shipping') === null && intval($addressId) ? $addressId === $defaultShippingId : $addressModel->getData('is_default_shipping'); $this->_addressBuilder->populateWithArray(array_merge($addressData, array(Address::KEY_STREET => $addressModel->getStreet(), Address::KEY_DEFAULT_BILLING => $isDefaultBilling, Address::KEY_DEFAULT_SHIPPING => $isDefaultShipping, Address::KEY_REGION => array(Region::KEY_REGION => $addressModel->getRegion(), Region::KEY_REGION_ID => $addressModel->getRegionId(), Region::KEY_REGION_CODE => $addressModel->getRegionCode())))); if ($addressId) { $this->_addressBuilder->setId($addressId); } if ($addressModel->getCustomerId() || $addressModel->getParentId()) { $customerId = $addressModel->getCustomerId() ?: $addressModel->getParentId(); $this->_addressBuilder->setCustomerId($customerId); } $addressDataObject = $this->_addressBuilder->create(); return $addressDataObject; }
/** * Initialize form object * * @return $this * * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function initForm() { $customerData = $this->_backendSession->getCustomerData(); /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $fieldset = $form->addFieldset('address_fieldset', array('legend' => __("Edit Customer's Address"))); $account = $customerData['account']; $this->_addressBuilder->populateWithArray(array()); if (!empty($account) && isset($account['store_id'])) { $this->_addressBuilder->setCountryId($this->_coreData->getDefaultCountry($this->_storeManager->getStore($account['store_id']))); } else { $this->_addressBuilder->setCountryId($this->_coreData->getDefaultCountry()); } $address = $this->_addressBuilder->create(); $addressForm = $this->_metadataFormFactory->create('customer_address', 'adminhtml_customer_address', AddressConverter::toFlatArray($address)); $attributes = $addressForm->getAttributes(); if (isset($attributes['street'])) { if ($attributes['street']->getMultilineCount() <= 0) { $attributes['street'] = $this->_attributeMetadataBuilder->populate($attributes['street'])->setMultilineCount(self::DEFAULT_STREET_LINES_COUNT)->create(); } } foreach ($attributes as $key => $attribute) { $attributes[$key] = $this->_attributeMetadataBuilder->populate($attribute)->setFrontendLabel(__($attribute->getFrontendLabel()))->setVisible(false)->create(); } $this->_setFieldset($attributes, $fieldset); $regionElement = $form->getElement('region'); if ($regionElement) { $regionElement->setRenderer($this->_regionFactory->create()); } $regionElement = $form->getElement('region_id'); if ($regionElement) { $regionElement->setNoDisplay(true); } $country = $form->getElement('country_id'); if ($country) { $country->addClass('countries'); } if ($this->isReadonly()) { foreach ($this->_metadataService->getAllAddressAttributeMetadata() as $attribute) { $element = $form->getElement($attribute->getAttributeCode()); if ($element) { $element->setReadonly(true, true); } } } $customerStoreId = null; if (!empty($account) && isset($account['id']) && isset($account['website_id'])) { $customerStoreId = $this->_storeManager->getWebsite($account['website_id'])->getDefaultStore()->getId(); } $prefixElement = $form->getElement('prefix'); if ($prefixElement) { $prefixOptions = $this->_customerHelper->getNamePrefixOptions($customerStoreId); if (!empty($prefixOptions)) { $fieldset->removeField($prefixElement->getId()); $prefixField = $fieldset->addField($prefixElement->getId(), 'select', $prefixElement->getData(), '^'); $prefixField->setValues($prefixOptions); } } $suffixElement = $form->getElement('suffix'); if ($suffixElement) { $suffixOptions = $this->_customerHelper->getNameSuffixOptions($customerStoreId); if (!empty($suffixOptions)) { $fieldset->removeField($suffixElement->getId()); $suffixField = $fieldset->addField($suffixElement->getId(), 'select', $suffixElement->getData(), $form->getElement('lastname')->getId()); $suffixField->setValues($suffixOptions); } } $this->assign('customer', $this->_customerBuilder->populateWithArray($account)->create()); $addressCollection = array(); foreach ($customerData['address'] as $key => $addressData) { $addressCollection[$key] = $this->_addressBuilder->populateWithArray($addressData)->create(); } $this->assign('addressCollection', $addressCollection); $form->setValues(AddressConverter::toFlatArray($address)); $this->setForm($form); return $this; }
/** * @param string $attributeCode * @return Data\Eav\AttributeMetadata|null */ private function getAttributeMetadata($attributeCode) { try { return $this->customerMetadataService->getCustomerAttributeMetadata($attributeCode); } catch (NoSuchEntityException $e) { return null; } }