英文:
Access to custom fields in match() function of a Rule Plugin
问题
我尝试构建一个规则插件,用于检查产品的自定义字段。
我不知道从哪里开始。在扩展Shopware\Core\Framework\Rule\Rule
的class
的match()
函数内,如何访问产品对象和自定义字段?
英文:
I try to build a Rule plugin, that checks a custom field of a product.
I do not know where to start here. How can I get access to the product object and the custom fields from inside the match()
function of a class
that extends Shopware\Core\Framework\Rule\Rule
答案1
得分: 1
查看如何添加自定义规则条件的文档。
要了解如何在Rule
扩展中访问自定义字段,请参考LineItemCustomFieldRule
。
在match
方法中,请检查范围是LineItemScope
或CartRuleScope
的实例。在CartRuleScope
情况下,您可以迭代购物车中的商品项。
自定义字段存储在商品项的有效载荷中。
在match
方法中匹配特定自定义字段的通用示例:
if ($scope instanceof LineItemScope) {
$customFields = $scope->getLineItem()->getPayloadValue('customFields');
return $this->customFieldMatches($customFields['my_custom_field'] ?? null);
}
if (!$scope instanceof CartRuleScope) {
return false;
}
foreach ($scope->getCart()->getLineItems()->filterGoodsFlat() as $lineItem) {
$customFields = $lineItem->getPayloadValue('customFields');
if ($this->customFieldMatches($customFields['my_custom_field'] ?? null)) {
return true;
}
}
return false;
显然,customFieldMatches
是您需要自己实现的,其逻辑决定是否满足条件。
英文:
See the documentation on how to add a custom rule condition.
For reference on how to access the custom fields within the Rule
extension, see LineItemCustomFieldRule
.
Within the match
method check that the scope is either an instance of LineItemScope
or CartRuleScope
. In case of CartRuleScope
you can iterate the line items in the cart.
The custom fields are stored within the payload of the line items.
Generalized example to match a specific custom field within the match
method:
if ($scope instanceof LineItemScope) {
$customFields = $scope->getLineItem()->getPayloadValue('customFields');
return $this->customFieldMatches($customFields['my_custom_field'] ?? null);
}
if (!$scope instanceof CartRuleScope) {
return false;
}
foreach ($scope->getCart()->getLineItems()->filterGoodsFlat() as $lineItem) {
$customFields = $lineItem->getPayloadValue('customFields');
if ($this->customFieldMatches($customFields['my_custom_field'] ?? null)) {
return true;
}
}
return false;
Obviously customFieldMatches
is what you would have to implement yourself with the logic that denotes whether a condition is met or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论