Magento 2.2.1 - как предоставить скидку на способы оплаты?
2 answers
У меня есть код ядра отладки для этой проблемы и я нахожу ошибку в файле Magento\SalesRule\Model\Rule\Condition\Address.php
в номере строки:58
Решение:
Заменить код в функции loadAttributeOptions
от
public function loadAttributeOptions()
{
$attributes = [
'base_subtotal' => __('Subtotal'),
'total_qty' => __('Total Items Quantity'),
'weight' => __('Total Weight'),
'shipping_method' => __('Shipping Method'),
'postcode' => __('Shipping Postcode'),
'region' => __('Shipping Region'),
'region_id' => __('Shipping State/Province'),
'country_id' => __('Shipping Country'),
];
$this->setAttributeOption($attributes);
return $this;
}
Чтобы
public function loadAttributeOptions()
{
$attributes = [
'base_subtotal' => __('Subtotal'),
'total_qty' => __('Total Items Quantity'),
'weight' => __('Total Weight'),
'shipping_method' => __('Shipping Method'),
'payment_method' => __('Payment Method'),
'postcode' => __('Shipping Postcode'),
'region' => __('Shipping Region'),
'region_id' => __('Shipping State/Province'),
'country_id' => __('Shipping Country'),
];
$this->setAttributeOption($attributes);
return $this;
}
Примечание: Первый файл модели переопределения Address.php
в локальном после обновления вышеуказанного кода в файле.
Переопределение кода файла модели:
App\code\AR\SalesRule\etc\module.xml
<?xml version="1.0"?>
<!--
/**
* Copyright © 2015 Ccc. All rights reserved.
*/
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="AR_SalesRule" setup_version="1.0.0">
<sequence>
<module name="Magento_SalesRule"/>
</sequence>
</module>
</config>
App\code\AR\SalesRule\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\SalesRule\Model\Rule\Condition\Address" type="AR\SalesRule\Model\Rule\Condition\Address" />
</config>
App\code\AR\SalesRule\Model\Rule\Condition\Address.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace AR\SalesRule\Model\Rule\Condition;
class Address extends \Magento\SalesRule\Model\Rule\Condition\Address
{
/**
* Load attribute options
*
* @return $this
*/
public function loadAttributeOptions()
{
$attributes = [
'base_subtotal' => __('Subtotal'),
'total_qty' => __('Total Items Quantity'),
'weight' => __('Total Weight'),
'shipping_method' => __('Shipping Method'),
'payment_method' => __('Payment Method'),
'postcode' => __('Shipping Postcode'),
'region' => __('Shipping Region'),
'region_id' => __('Shipping State/Province'),
'country_id' => __('Shipping Country'),
];
$this->setAttributeOption($attributes);
return $this;
}
}
App\code\AR\SalesRule\registration.php
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'AR_SalesRule',
__DIR__
);
После выполнения приведенной ниже команды:
Настройка Php bin/magento: обновление
Спасибо Абдулу за подсказку и отладку.
Я думаю, что в первую очередь следует рассмотреть возможность использования плагина/перехватчика для добавления некоторых дополнительных функций в основные файлы. Если это не удается или невозможно, используйте метод переопределения. С помощью перехватчиков вы не потеряете будущие обновления Magento\SalesRule\Model\Rule\Condition\Adress::loadAttributeOptions()
.
Если Magento добавит некоторые новые опции в основную функцию, вам будет не хватать опции в вашей переопределяющей модели, поэтому вам нужно снова коснуться кода.
По крайней мере, при использовании метод переопределения я бы попытался вызвать родительский метод и объединить базовые параметры с моей новой опцией, что-то вроде этого
parent::loadAttributeOptions();
$this->setAttributeOption(array_merge(
$this->getAttributeOption(),
['payment_method' => __('Payment Method'))
);
Пример добавления "Способа оплаты" в правила корзины с помощью плагина/перехватчика
В своем пользовательском расширении добавьте следующее файлы:
- приложение/код/ ВАШ/ДОБАВОЧНЫЙ НОМЕР/etc/di.xml
- приложение/код/ ВАШ/ДОБАВОЧНЫЙ НОМЕР/Plugin/SalesRule/AdressPlugin.php
App/code/Your/Extension/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\SalesRule\Model\Rule\Condition\Address">
<plugin name="Your_Extension_Plugin_SalesRule_Address" type="Your\Extension\Plugin\SalesRule\AddressPlugin" sortOrder="10" disabled="false" />
</type>
</config>
App/code/Your/Extension/Plugin/SalesRule/AdressPlugin.php:
<?php
namespace Your\Extension\Plugin\SalesRule;
use Magento\SalesRule\Model\Rule\Condition\Address;
class AddressPlugin
{
/**
* Your Description.
*
* @param Address
*
* @return Address
*/
public function afterLoadAttributeOptions(Address $subject)
{
$options = $subject->getAttributeOption();
if (!array_key_exists('payment_method', $options)) {
$subject->setAttributeOption(array_merge($options, ['payment_method' => __('Payment Method')]));
}
return $subject;
}
}