Get display node id for a commerce product

Public

Use this function anytime you need to get a display node id for a product. Put it into your custom module.

Get raw version
php
  1. /**
  2.  * Get display node id for a commerce product.
  3.  * @param $product_id
  4.  * An integer value of the product id.
  5.  * @param string $product_field_name
  6.  * Name of the commerce_product_reference field used to reference products from display node.
  7.  * @return FALSE|node_id
  8.  * Returns FALSE if no results or display node id on success.
  9.  */
  10. function MY_CUSTOM_MODULE_get_display_node_by_product_id($product_id, $product_field_name = 'product_reference') {
  11. $query = new EntityFieldQuery;
  12. $result = $query->entityCondition('entity_type', 'node', '=')
  13. ->propertyCondition('type', 'tire')
  14. ->fieldCondition($product_field_name, 'product_id', $product_id, '=')
  15. ->range(0, 1)->execute();
  16.  
  17. if (empty($result['node'])) {
  18. return FALSE;
  19. }
  20.  
  21. return reset($result['node'])->nid;
  22. }

Comments

rcross's picture

what if you get more than 1 result?

Sweetchuck's picture

Hello

Nice snippet, but what if more than one display node points to the same product?

timonweb's picture

In this case instead of line 21 you can do something like:

  1. $nids = array();
  2. foreach ($result['node'] as $node) {
  3. $nids[] = $node->nid;
  4. }
  5. return $nids;