如何在Rule插件的match()函数中访问自定义字段
在Shopware Rule插件中获取商品对象及自定义字段
1. 明确RuleScope类型
Shopware的Rule类match()方法接收的RuleScope参数会随业务场景变化:
- 针对商品本身(如商品列表筛选、商品详情页规则),传入的是
ProductRuleScope - 针对购物车中的商品(如促销规则),传入的是
CartRuleScope
需先判断当前Scope类型,再针对性获取商品对象。
2. 获取商品对象
针对ProductRuleScope场景
直接从Scope提取商品实体:
public function match(RuleScope $scope): bool { // 非商品场景直接返回不匹配 if (!$scope instanceof ProductRuleScope) { return false; } // 获取商品实体(ProductEntity) $product = $scope->getProduct(); }
针对CartRuleScope场景
遍历购物车商品项,从每个项的Payload中提取商品实体:
public function match(RuleScope $scope): bool { if (!$scope instanceof CartRuleScope) { return false; } $cart = $scope->getCart(); // 筛选购物车中的商品类型项 foreach ($cart->getLineItems()->filterType('product') as $lineItem) { /** @var \Shopware\Core\Content\Product\ProductEntity $product */ $product = $lineItem->getPayloadValue('product'); // 对单个商品进行自定义字段检查 } }
3. 获取商品自定义字段
商品实体ProductEntity提供getCustomFields()方法,直接返回自定义字段的关联数组:
// 获取全部自定义字段 $customFields = $product->getCustomFields(); // 获取指定自定义字段的值(用??避免未定义键报错) $targetValue = $customFields['your_custom_field_key'] ?? null;
完整示例代码
以下是一个完整的Rule类,用于检查商品指定自定义字段是否匹配目标值:
<?php namespace YourPlugin\Rule; use Shopware\Core\Framework\Rule\Rule; use Shopware\Core\Framework\Rule\RuleScope; use Shopware\Core\Framework\Rule\ProductRuleScope; use Symfony\Component\Validator\Constraints\NotBlank; class ProductCustomFieldMatchRule extends Rule { // 可配置的规则参数:自定义字段键、目标匹配值 protected string $customFieldKey; protected string $targetValue; public function __construct(string $customFieldKey = '', string $targetValue = '') { parent::__construct(); $this->customFieldKey = $customFieldKey; $this->targetValue = $targetValue; } public function match(RuleScope $scope): bool { if (!$scope instanceof ProductRuleScope) { return false; } $product = $scope->getProduct(); $customFields = $product->getCustomFields(); // 检查字段存在且值匹配 return isset($customFields[$this->customFieldKey]) && $customFields[$this->customFieldKey] === $this->targetValue; } public function getName(): string { return 'product_custom_field_match'; } public function getConstraints(): array { // 为规则参数添加必填验证 return [ 'customFieldKey' => new NotBlank(), 'targetValue' => new NotBlank(), ]; } }
额外注意事项
- 需在插件的
services.xml中注册该Rule类:<service id="YourPlugin\Rule\ProductCustomFieldMatchRule" public="true"> <tag name="shopware.rule"/> </service> - 若需在后台规则编辑器可视化配置,需在
src/Resources/config.xml中添加UI配置,定义参数的输入控件。
内容的提问来源于stack exchange,提问作者Jürgen Hörmann
相关产品推荐
相关产品推荐

