Drupal commerce - 以编程方式验证产品优惠券

时间:2014-07-17 13:21:27

标签: drupal drupal-7 coupon commerce

我的所有产品都与某些“杂志”内容类型对象相关 - 即每个产品都有对Magazine对象的节点引用。此外,我将相同的节点参考字段添加到优惠券,再次引用“杂志”内容类型的节点。我想要达到的目标是获得仅适用于某些杂志的优惠券。如果优惠券杂志匹配产品杂志优惠券是有效的。其他方式不是。我不能用规则做到这一点,因为我不能以任何方式接近该产品的杂志领域。我所能看到的只是订单项,我无法进一步了解产品。我希望我能从代码中做到这一点。有没有办法以编程方式设置某个优惠券是否有效。

我只是想通过所有订单项,检查其中一些是否与优惠券一样具有相同的杂志集。

我也想知道将优惠券与单品或订单项联系起来是否有意义?

1 个答案:

答案 0 :(得分:0)

我不完全确定我会遵循此说明,但如果它是产品系列产品,您应该能够访问产品ID,并加载产品并检查有效的杂志。

或者,您可以执行的操作是为允许杂志的优惠券类型添加一个字段,其中包含杂志节点/产品的实体参考字段。然后,通过代码或通过规则,检查订单项的产品到该特定优惠券的可接受杂志列表。通过您自己的验证或计算方法调用此代码。即。您可以在代码中创建自定义优惠券,也可以添加规则来验证“杂志优惠券”类型的优惠券,并在规则中调用一些自定义的PHP代码。

// ** note: this is totally untested/rough code **
// Just to give you an idea of how it *could* work 

// assuming we have a $coupon and a $line_item at this point 

// some basic set up
$coupon_wrapper = entity_metadata_wrapper('commerce_coupon', $coupon);
$line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

$product_id = $line_item_wrapper->product_id->raw();
$product = commerce_product_load($product_id);
$product_wrapper = entity_metadata_wrapper('commerce_product', $product);

$magazine_id = $product_wrapper->magazine->nid->raw();
$eligible_magazines = $coupon_wrapper->coupon_magazines->value();

// for each eligible product on the list from the coupon
for($i = 0; $i < count($eligible_products); $i++) {   

    // compare our product's magazine value to the eligible magazine id
    if($eligible_magazines[$i]->nid  == $magazine_id) {
        // do stuff here, whether return true for the validation etc
    }
}

或者,如果您只有订单,则可以执行非常类似的操作并循环订单中的订单项。订单只有我认为的ID,所以你必须使用commerce_line_item_load函数。

在评论中回答你的问题 - 是的,您可以添加一个钩子来在模块中执行此代码,也可以创建一个规则来执行此操作。 - 您可以为优惠券添加验证规则,例如

(再次未经测试)

{ "rules_coupon_check_magazine" : {
    "LABEL" : "Coupon: Check Magazine",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "php", "commerce_coupon" ],
    "ON" : [ "commerce_coupon_validate" ],
    "IF" : [
      {"entity_has_field" : {
      "entity" : [ "commerce-order" ],
      "field" : "commerce_coupon_order_reference"
    }
  },
  { "NOT data_is_empty" : { "data" : [ "commerce-order:commerce-coupon-order-reference" ] } },
      { "php_eval" : { "code" : "\/\/ my validation code here - either return true or false\r\nreturn true;" } }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, you cannot apply this coupon to the order",
          "type" : "error"
        }
      },
      { "commerce_coupon_action_is_invalid_coupon" : [] }
    ]
  }
}
相关问题