2

In Drupal Commerce, using programming, what is the way to grab the product SKU of the product entity that is about to fire off and display on the page in a product display node, as early as possible? I'm looking for something that is before panes and views are executed and drawn.

I know the SKU lives in $form_state['default_product']->sku within a hook_form_alter, but that is too late.

In panels, I know there is a time in hook_panels_pane_content_alter where I can scrape the SKU out of $content->content['#markup']. That doesn't seem to update though as I change the selectors that affect which product is currently displaying. So that's no good.

I need it as early as possible, because I want to pass that value into a view during hook_views_pre_view, which is executed very early.

1

Have you tried using menu_get_object? It provides access to objects loaded by the current router item.

Once you've got the node, the product reference field is just going to list the products and Drupal Commerce may exclude products from the add to cart form based on rules and other modules. But you can get the SKU of the first referenced product on the product display like this:

$node = menu_get_object(); // May want to check that it's a node.
$node = entity_metadata_wrapper('node', $node);
$products = $node->field_product->get(0)->sku->value(); // field_product is my product reference, may want to check that it exists.
  • You showed how I can get the sku of the first product, but I'm after the sku of the current product, an important distinction. As I change selectors on the product display, and that results in a different product SKU showing on the screen, I want to be able to grab that sku value in code as soon as possible. For my specific need, it's so I can pass that SKU value as an arg to a view. So it needs to be something that executes everytime a new SKU is about to show, and it needs to be something that executes earlier than the view hook I am using. – Chad Feb 7 '14 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.