php - 应用目录价格规则时,Magento 2 Plugin afterGetPrice 不起作用
问题描述
我创建了一个简单的 Magento 2 插件,这增加了价格。
这是我测试过的简单代码
<?php
namespace [Vendor]\[Name]\Plugin\Magento\Catalog\Model;
class Product
{
protected $objectManager;
public function __construct(
\Magento\Framework\ObjectManagerInterface $objectManager
)
{
$this->objectManager = $objectManager;
}
public function afterGetPrice(
\Magento\Catalog\Model\Product $subject,
$result
) {
return $result + 100;
}
}
这段代码工作正常,但是当我创建目录价格规则时,系统就像它不使用它,而是从另一个模块中获取价格。有没有人已经遇到过这个问题并找到了解决方案?我想了解并解决问题。
提前致谢。
解决方案
I solved the problem.
In practice in module-catalog-rule/Model/Indexer/ProductPriceCalculator:
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\CatalogRule\Model\Indexer;
/**
* Product price calculation according rules settings.
*/
class ProductPriceCalculator
{
/**
* @var \Magento\Framework\Pricing\PriceCurrencyInterface
*/
private $priceCurrency;
/**
* @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency
*/
public function __construct(\Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency)
{
$this->priceCurrency = $priceCurrency;
}
/**
* Calculates product price.
*
* @param array $ruleData
* @param null $productData
* @return float
*/
public function calculate($ruleData, $productData = null)
{
if ($productData !== null && isset($productData['rule_price'])) {
$productPrice = $productData['rule_price'];
} else {
$productPrice = $ruleData['default_price'];
}
switch ($ruleData['action_operator']) {
case 'to_fixed':
$productPrice = min($ruleData['action_amount'], $productPrice);
break;
case 'to_percent':
$productPrice = $productPrice * $ruleData['action_amount'] / 100;
break;
case 'by_fixed':
$productPrice = max(0, $productPrice - $ruleData['action_amount']);
break;
case 'by_percent':
$productPrice = $productPrice * (1 - $ruleData['action_amount'] / 100);
break;
default:
$productPrice = 0;
}
return $this->priceCurrency->round($productPrice);
}
}
The calculate function ($ruleData, $ProductData = null) performs the calculations set in the catalog rule.
The real problem lies in $ruleData, because the price information it contains is taken directly from the product_catalog database, excluding any plugin designed to modify the price.
I personally don't know, if this is a Magento 2 bug or not, but the only way to make the module catalog rule work is just to intercept that variable and modify its contents.
I hope it helps someone. :)
Ps. sorry for my bad English
推荐阅读
- java - 我正在阅读“Java 编程和数据结构简介”一书,在解释类抽象和封装的章节中,它说:
- node.js - 如何在 Mongoose 中正确格式化 API 响应?
- javascript - 做一些freecodecamp问题,我遇到了一个指导对象值的小问题
- graphql - 阿波罗,Next.js,Strapi,GraphQL 错误'
. ' 在方案或关系中找不到 - javascript - Javascript从电报中保存用户名
- javascript - 在angularJs的自定义指令中观察错误抛出错误
- vue.js - Safari 上未显示 Vuetify mdi 图标
- javascript - 如何在反应中将道具传递给多级组件?
- javascript - 脚本未从外部文件加载 css 属性
- postgresql - PostgreSQL Group By 查询结果不显示组值,只显示列名