【问题标题】:Magento Address Templates Region CodeMagento 地址模板区域代码
【发布时间】:2023-03-12 13:34:01
【问题描述】:

我正在 Magento (v.1.9.2.4) 中创建一个网站,我想仅使用区域代码而不是整个区域名称来格式化地址(例如:罗德岛到 RI)

我知道模板位于Customer Configuration > Address Templates

{{depend prefix}}{{var prefix}} {{/depend}}{{var firstname}} {{depend middlename}}{{var middlename}} {{/depend}}{{var lastname} }{{依赖后缀}} {{var 后缀}}{{/depend}}
{{depend company}}{{var company}}
{{/depend}} {{if street1}}{{var street1}}
{{/if}} {{depend street2}}{{var street2}}
{{/depend}} {{depend street3}}{{var street3}}
{{/depend}} {{depend street4}}{{var street4}}
{{/depend}} {{if city}}{{var city}}, {{/if}}{{if region}}{{var region}}, {{/if}}{{if postcode}}{{var postcode}} {{/if}}
{{var 国家/地区}}
{{depend 电话}}电话:{{var 电话}}{{/depend}} {{依赖传真}}
F: {{var 传真}}{{/depend}} {{depend vat_id}}
增值税:{{var vat_id}}{{/depend}}`

但是当我将{{if region}}{{var region}} 更改为{{if regioncode}}{{var regioncode}}{{if region_code}}{{var region_code}} 时,它不起作用。

有人可以帮助我吗? 我也尝试搜索字段列表,但找不到任何内容。

谢谢

【问题讨论】:

    标签: magento


    【解决方案1】:

    regioncode 不是客户地址属性。只有 region 和 region_id 可用。

    {{/if}}{{if region}}{{var region}}

    将显示完整的地区名称,例如加利福尼亚 我们可以覆盖本地文件夹中的地址块并自定义代码以显示区域代码,如 CA。

    更改客户地址模板:

    系统->配置->客户->客户配置

    并向下滚动到地址模板并进行编辑:

    {{/if}}{{if region}}{{var region}} 替换为 {{/if}}{{if region_id}}{{var region_id}}

    覆盖块复制

    ‘app/code/core/Mage/Customer/Block/Address/Renderer/Default.php’

    进入

    ‘app/code/local/Mage/Customer/Block/Address/Renderer/Default.php’

    。这样做只会让 magento 从本地文件夹而不是核心文件夹中读取此文件,并更改 render() 方法如下:

    public function render(Mage_Customer_Model_Address_Abstract $address, $format=null)
        {
            switch ($this->getType()->getCode()) {
                case 'html':
                    $dataFormat = Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_HTML;
                    break;
                case 'pdf':
                    $dataFormat = Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_PDF;
                    break;
                case 'oneline':
                    $dataFormat = Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_ONELINE;
                    break;
                default:
                    $dataFormat = Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_TEXT;
                    break;
            }
    
            $formater   = new Varien_Filter_Template();
            $attributes = Mage::helper('customer/address')->getAttributes();
    
            $data = array();
            foreach ($attributes as $attribute) {
                /* @var $attribute Mage_Customer_Model_Attribute */
                if (!$attribute->getIsVisible()) {
                    continue;
                }
                if ($attribute->getAttributeCode() == 'country_id') {
                    $data['country'] = $address->getCountryModel()->getName();
                } else if ($attribute->getAttributeCode() == 'region') {
                    $data['region'] = Mage::helper('directory')->__($address->getRegion());
                }else if ($attribute->getAttributeCode() == 'region_id') {
    

    $data['region_id'] = Mage::helper('directory')->__($address->getRegionCode());

                } else {
                    $dataModel = Mage_Customer_Model_Attribute_Data::factory($attribute, $address);
                    $value     = $dataModel->outputValue($dataFormat);
                    if ($attribute->getFrontendInput() == 'multiline') {
                        $values    = $dataModel->outputValue(Mage_Customer_Model_Attribute_Data::OUTPUT_FORMAT_ARRAY);
                        // explode lines
                        foreach ($values as $k => $v) {
                            $key = sprintf('%s%d', $attribute->getAttributeCode(), $k + 1);
                            $data[$key] = $v;
                        }
                    }
                    $data[$attribute->getAttributeCode()] = $value;
                }
            }
    
            if ($this->getType()->getHtmlEscape()) {
                foreach ($data as $key => $value) {
                    $data[$key] = $this->escapeHtml($value);
                }
            }
    
            $formater->setVariables($data);
    
            $format = !is_null($format) ? $format : $this->getFormat($address);
    
            return $formater->filter($format);
        }
    

    【讨论】:

      【解决方案2】:

      如果有人还在寻找解决方案,您还可以添加一个helper 类来将区域转换为区域代码并在您的块中调用辅助函数。

      示例

      假设您已经创建了自定义模块

      包/模块/Helper/Data.php

      <?php
      namespace Package\Module\Helper;
      use Magento\Directory\Model\ResourceModel\Region\Collection;
      use Magento\Directory\Model\ResourceModel\Region\CollectionFactory;
      
      class Data extends \Magento\Framework\App\Helper\AbstractHelper
      {
          /**
           * @var Collection
           */
          private $collectionFactory;
      
          public function __construct(
              CollectionFactory $collectionFactory
          ) {
              $this->collectionFactory = $collectionFactory;
          }
      
          /**
           * @param string $region
           * @return string[]
           */
          public function getRegionCode(string $region): array
          {
              $regionCode = $this->collectionFactory->create()
                  ->addRegionNameFilter($region)
                  ->getFirstItem()
                  ->toArray();
              return $regionCode;
          }
      }
      

      现在需要覆盖你的核心模块 包/模块/etc/di.xml

      <?xml version="1.0"?>
      <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
          <preference for="Magento\Customer\Block\Address\Renderer\DefaultRenderer" type="Package\Module\Block\Address\Renderer\DefaultRenderer"/>
      </config>
      

      最后是您的自定义块 包/模块/块/地址/Renderer/DefaultRenderer.php

      <?php
      /**
       * Copyright © Magento, Inc. All rights reserved.
       * See COPYING.txt for license details.
       */
      namespace Package\module\Block\Address\Renderer;
      
      use Magento\Customer\Block\Address\Renderer\RendererInterface;
      use Magento\Customer\Model\Address\AddressModelInterface;
      use Magento\Customer\Model\Address\Mapper;
      use Magento\Customer\Model\Metadata\ElementFactory;
      use Magento\Directory\Model\Country\Format;
      use Magento\Framework\View\Element\AbstractBlock;
      use Magento\TestFramework\Event\Magento;
      use Package\module\Helper\Data;
      
      /**
       * Address format renderer default
       */
      class DefaultRenderer extends AbstractBlock implements RendererInterface
      {
          /**
           * Format type object
           *
           * @var \Magento\Framework\DataObject
           */
          protected $_type;
      
          /**
           * @var ElementFactory
           */
          protected $_elementFactory;
      
          /**
           * @var \Magento\Directory\Model\CountryFactory
           */
          protected $_countryFactory;
      
          /**
           * @var \Magento\Customer\Api\AddressMetadataInterface
           */
          protected $_addressMetadataService;
      
          /**
           * @var Mapper
           */
          protected $addressMapper;
      
          /**
           * Constructor
           *
           * @param \Magento\Framework\View\Element\Context $context
           * @param ElementFactory $elementFactory
           * @param \Magento\Directory\Model\CountryFactory $countryFactory
           * @param \Magento\Customer\Api\AddressMetadataInterface $metadataService
           * @param Mapper $addressMapper
           * @param array $data
           */
          public function __construct(
              \Magento\Framework\View\Element\Context $context,
              ElementFactory $elementFactory,
              \Magento\Directory\Model\CountryFactory $countryFactory,
              \Magento\Customer\Api\AddressMetadataInterface $metadataService,
              Mapper $addressMapper,
              array $data = [],
              Data $helper
          ) {
              $this->_elementFactory = $elementFactory;
              $this->_countryFactory = $countryFactory;
              $this->_addressMetadataService = $metadataService;
              $this->addressMapper = $addressMapper;
              parent::__construct($context, $data);
              $this->_isScopePrivate = true;
              $this->helper = $helper;
          }
      
          /**
           * Retrieve format type object
           *
           * @return \Magento\Framework\DataObject
           */
          public function getType()
          {
              return $this->_type;
          }
      
          /**
           * Retrieve format type object
           *
           * @param  \Magento\Framework\DataObject $type
           * @return \Magento\Customer\Block\Address\Renderer\DefaultRenderer
           */
          public function setType(\Magento\Framework\DataObject $type)
          {
              $this->_type = $type;
              return $this;
          }
      
          /**
           * Get the format of the address
           *
           * @param AddressModelInterface|null $address
           * @return string
           * All new code should use renderArray based on Metadata service
           */
          public function getFormat(AddressModelInterface $address = null)
          {
              $countryFormat = $address === null
                  ? false : $address->getCountryModel()->getFormat(
                      $this->getType()->getCode()
                  );
              $format = $countryFormat ? $countryFormat->getFormat() : $this->getType()->getDefaultFormat();
              return $format;
          }
      
          /**
           * Render address
           *
           * @param AddressModelInterface $address
           * @param string|null $format
           * @return mixed
           * @SuppressWarnings(PHPMD.CyclomaticComplexity)
           * @SuppressWarnings(PHPMD.NPathComplexity)
           */
          public function render(AddressModelInterface $address, $format = null)
          {
              $address = $address->getDataModel(0, 0);
              return $this->renderArray($this->addressMapper->toFlatArray($address), $format);
          }
      
          /**
           * @inheritdoc
           */
          public function getFormatArray($addressAttributes = null)
          {
              $countryFormat = false;
              if ($addressAttributes && isset($addressAttributes['country_id'])) {
                  /** @var \Magento\Directory\Model\Country $country */
                  $country = $this->_countryFactory->create()->load($addressAttributes['country_id']);
                  $countryFormat = $country->getFormat($this->getType()->getCode());
              }
              $format = $countryFormat ? $countryFormat->getFormat() : $this->getType()->getDefaultFormat();
              return $format;
          }
      
          /**
           * Render address by attribute array
           *
           * @param array $addressAttributes
           * @param Format|null $format
           * @return string
           * @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->_addressMetadataService->getAllAttributesMetadata();
              $data = [];
              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'] = (string)__($addressAttributes['region']);
                      $regionName = $addressAttributes['region'];
                      $regionData= $this->helper->getRegionCode($regionName);
                      $regionArray = $regionData;
                      $data['region_code'] = $regionArray['code'];
      
                  } 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 = $format !== null ? $format : $this->getFormatArray($addressAttributes);
              return $this->filterManager->template($format, ['variables' => $data]);
          }
      }
      

      【讨论】:

      • 请同时添加一个示例说明如何操作。接受的答案很好地描述了它。您的答案应该为实际接受的答案添加新内容。
      • 我已添加示例代码,请查看。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 2018-08-05
      相关资源
      最近更新 更多