在Rule插件的match()函数中访问自定义字段。

huangapple go评论63阅读模式
英文:

Access to custom fields in match() function of a Rule Plugin

问题

我尝试构建一个规则插件,用于检查产品的自定义字段。

我不知道从哪里开始。在扩展Shopware\Core\Framework\Rule\Ruleclassmatch()函数内,如何访问产品对象和自定义字段?

英文:

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方法中,请检查范围是LineItemScopeCartRuleScope的实例。在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.

huangapple
  • 本文由 发表于 2023年5月26日 17:05:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76339290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定