Synchronise Commerce product and display node status

Public

When you disable a product in Drupal Commerce, the product display nodes that reference that product are still published; they simply disable the 'Add to cart' button.

This Rule synchronises the status of the product and the display node(s) so that disabling a product also unpublishes the node(s).

</> CopyGet raw version
text
  1. { "rules_synchronise_product_node_status" : {
  2. "LABEL" : "Synchronise product \u0026 node status",
  3. "PLUGIN" : "reaction rule",
  4. "WEIGHT" : "10",
  5. "REQUIRES" : [ "php", "rules", "entity" ],
  6. "ON" : [ "commerce_product_presave" ],
  7. "DO" : [
  8. { "php_eval" : { "code" : "\u002F\u002F Get new status from product\u000D\u000A$new_status = $commerce_product-\u003Estatus;\u000D\u000A\u000D\u000A\u002F\u002F Get all nodes that reference this product\u000D\u000A$query = new EntityFieldQuery();\u000D\u000A$query-\u003EentityCondition(\u0027entity_type\u0027, \u0027node\u0027)\u000D\u000A -\u003EentityCondition(\u0027bundle\u0027, \u0027product_display\u0027)\u000D\u000A -\u003EfieldCondition(\u0027field_product\u0027, \u0027product_id\u0027, $commerce_product-\u003Eproduct_id, \u0027=\u0027);\u000D\u000A$result = $query-\u003Eexecute();\u000D\u000A\u000D\u000Aif (isset($result[\u0027node\u0027])) {\u000D\u000A $nids = array_keys($result[\u0027node\u0027]);\u000D\u000A $nodes = entity_load(\u0027node\u0027, $nids);\u000D\u000A\u000D\u000A \u002F\u002F Change status on nodes\u000D\u000A foreach ($nodes as $node) {\u000D\u000A $node-\u003Estatus = $new_status;\u000D\u000A node_save($node);\u000D\u000A }\u000D\u000A}" } },
  9. { "drupal_message" : { "message" : "\u003C?php\u000D\u000A$product_status = ($commerce_product-\u003Estatus == 1) ? \u0027active\u0027 : \u0027disabled\u0027;\u000D\u000A$node_status = ($commerce_product-\u003Estatus == 1) ? \u0027published\u0027 : \u0027unpublished\u0027;\u000D\u000A?\u003E\u000D\u000AAll nodes that reference [commerce-product:title] have been \u003C?php print $node_status; ?\u003E to match its \u003C?php print $product_status; ?\u003E status." } }
  10. ]
  11. }
  12. }

Comments