Magento2 取消結帳頁必填欄位限制

適用版本: Magento2.0.X~2.3.X
本篇將介紹如何在Magento2的結帳頁面,取消原本需要必填的地址欄位,讓您可以因應不同的需求去限制使用者該填寫的欄位。
筆者認為Magento2的地址欄位設計比較是基於歐美國家設計的,所以當台灣的商家要使用Magento2當作EC平台時候,常會有不需要的必填地址欄位,而Magento2原本就有設計許多欄位可以依照後台設定去決定它該不該顯示、必填,設定的路徑為:Stores->Configuration->Customers->Customers Configuration->Name and Address Options

但是除了這些可以設定的欄位外,還是會有無法藉由後台設定,卻需要移除和取消必填的欄位,這些欄位就必須要修改程式碼來達成,筆者比較常遇到的是first name和last name,只需要留一個來填寫姓名就好,所以我們就用移除last name這個欄位來示範該如何去做。
- 因為2.3版本的驗證程式和2.2版的有些區別,在此會先列出適用2.3版本的程式碼,2.2版前適用的版本將會附上連結提供示範原始碼。
app/code/AstralWeb/ModifyAddress/etc/module.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> <module name="AstralWeb_ModifyAddress" setup_version="1.0.0"> <sequence> <module name="Magento_Checkout"/> <module name="Magento_Customer"/> </sequence> </module> </config>
app/code/AstralWeb/ModifyAddress/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"> <type name="Magento\Checkout\Block\Checkout\LayoutProcessor"> <plugin name="eslite_checkout_layout_processor" type="AstralWeb\ModifyAddress\Plugin\Block\LayoutProcessor" sortOrder="1"/> </type> <preference for="Magento\Customer\Model\Address\Validator\General" type="AstralWeb\ModifyAddress\Model\Address\Validator\General" /> </config>
此檔案執行移除結帳頁地址欄位
app/code/AstralWeb/ModifyAddress/Plugin/Block/LayoutProcessor.php
<?php
namespace AstralWeb\ModifyAddress\Plugin\Block;
use Magento\Checkout\Model\Session as CheckoutSession;
class LayoutProcessor
{
/**
* @var CheckoutSession
*/
public $checkoutSession;
/**
* @var null
*/
public $quote = null;
/**
* LayoutProcessor constructor.
* @param CheckoutSession $checkoutSession
*/
public function __construct(
CheckoutSession $checkoutSession
) {
$this->checkoutSession = $checkoutSession;
}
/**
* Get Quote
*
* @return \Magento\Quote\Model\Quote|null
*/
public function getQuote()
{
if (null === $this->quote) {
$this->quote = $this->checkoutSession->getQuote();
}
return $this->quote;
}
/**
* @param \Magento\Checkout\Block\Checkout\LayoutProcessor $subject
* @param array $jsLayout
* @return array
*/
public function aroundProcess(
\Magento\Checkout\Block\Checkout\LayoutProcessor $subject,
\Closure $proceed,
array $jsLayout
) {
$jsLayoutResult = $proceed($jsLayout);
if ($this->getQuote()->isVirtual()) {
return $jsLayoutResult;
}
//remove shipping address lastname
unset($jsLayoutResult['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['lastname']);
//remove billing address lastname
unset($jsLayoutResult['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['afterMethods']['children']['billing-address-form']['children']['form-fields']['children']['lastname']);
$configuration = $jsLayout['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['renders']['children'];
foreach ($configuration as $paymentGroup => $groupConfig) {
foreach ($groupConfig['methods'] as $paymentCode => $paymentComponent) {
unset($jsLayoutResult['components']['checkout']['children']['steps']['children']['billing-step']['children']['payment']['children']['payments-list']['children'][$paymentCode . '-form']['children']['form-fields']['children']['lastname']);
}
}
return $jsLayoutResult;
}
}
此檔案執行移除Server端地址欄位驗證
app/code/AstralWeb/ModifyAddress/Model/Address/Validator/General.php
<?php
namespace AstralWeb\ModifyAddress\Model\Address\Validator;
use Magento\Customer\Model\Address\AbstractAddress;
/**
* Address general fields validator.
*/
class General
{
/**
* @var \Magento\Eav\Model\Config
*/
private $eavConfig;
/**
* @var \Magento\Directory\Helper\Data
*/
private $directoryData;
/**
* @param \Magento\Eav\Model\Config $eavConfig
* @param \Magento\Directory\Helper\Data $directoryData
*/
public function __construct(
\Magento\Eav\Model\Config $eavConfig,
\Magento\Directory\Helper\Data $directoryData
) {
$this->eavConfig = $eavConfig;
$this->directoryData = $directoryData;
}
/**
* @inheritdoc
*/
public function validate(AbstractAddress $address)
{
$errors = array_merge(
$this->checkRequredFields($address),
$this->checkOptionalFields($address)
);
return $errors;
}
/**
* Check fields that are generally required.
*
* @param AbstractAddress $address
* @return array
* @throws \Zend_Validate_Exception
*/
private function checkRequredFields(AbstractAddress $address)
{
$errors = [];
if (!\Zend_Validate::is($address->getFirstname(), 'NotEmpty')) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'firstname']);
}
if (!\Zend_Validate::is($address->getStreetLine(1), 'NotEmpty')) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'street']);
}
if (!\Zend_Validate::is($address->getCity(), 'NotEmpty')) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'city']);
}
return $errors;
}
/**
* Check fields that are conditionally required.
*
* @param AbstractAddress $address
* @return array
* @throws \Magento\Framework\Exception\LocalizedException
* @throws \Zend_Validate_Exception
*/
private function checkOptionalFields(AbstractAddress $address)
{
$errors = [];
if ($this->isTelephoneRequired()
&& !\Zend_Validate::is($address->getTelephone(), 'NotEmpty')
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'telephone']);
}
if ($this->isFaxRequired()
&& !\Zend_Validate::is($address->getFax(), 'NotEmpty')
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'fax']);
}
if ($this->isCompanyRequired()
&& !\Zend_Validate::is($address->getCompany(), 'NotEmpty')
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'company']);
}
$havingOptionalZip = $this->directoryData->getCountriesWithOptionalZip();
if (!in_array($address->getCountryId(), $havingOptionalZip)
&& !\Zend_Validate::is($address->getPostcode(), 'NotEmpty')
) {
$errors[] = __('"%fieldName" is required. Enter and try again.', ['fieldName' => 'postcode']);
}
return $errors;
}
/**
* Check if company field required in configuration.
*
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isCompanyRequired()
{
return $this->eavConfig->getAttribute('customer_address', 'company')->getIsRequired();
}
/**
* Check if telephone field required in configuration.
*
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isTelephoneRequired()
{
return $this->eavConfig->getAttribute('customer_address', 'telephone')->getIsRequired();
}
/**
* Check if fax field required in configuration.
*
* @return bool
* @throws \Magento\Framework\Exception\LocalizedException
*/
private function isFaxRequired()
{
return $this->eavConfig->getAttribute('customer_address', 'fax')->getIsRequired();
}
}
然後最後記得要建立registration.php和composer.json檔案後執行安裝指令,就大功告成囉!
php bin/magento setup:upgrade; php bin/magento setup:di:compile; php bin/magento setup:static-content:deploy;
Github source code:
https://github.com/astraleason/ModifyAddressSample
以上是針對Magento2.3.0 MSI多源庫存的文章介紹,如果有您有更多疑問可以詢問我們,未來會撰寫更多電商網站相關文章,您想知道什麼嗎?歡迎在下方留言給我們。或追蹤我們的粉絲專頁,就不錯過最新文章喔!
想學習更多Magento設定嗎?請見:Magento教學導覽
我要留言