Question

I have a custom controller created for a custom URL, where the URL is a URL for an existing node with an additional parameter. The display for the URL defined by the controller needs to use the the same template for the base node route, and the controller just uses a service to get additional data and merge it with the base node data.

To be more specific, I have a node type called product_group. It has an entity reference field called field_products that attaches commerce_product entities. The URL alias pattern for product_group nodes is /products/[node-title]. My controller is for the URL /products/[node-title]/[sku], where sku is the commerce_product sku. The controller gets the data from the URL, loads the base product_group node object, uses the sku value to get the commerce_product object, and then I have a custom service that gets a bunch of additional data from the product and associated variation.

The tricky part is that the display at the /products/[node-title]/[sku] URL is the same as the display at the /products/[node-title] URL, with some additional data from the product itself added in. Therefore, I need to get all of the $variables data that is available in hook_preprocess_node() function in my controller and add my new data on top of it. The problem is, I can't figure how to access it. From what I've seen, you can't access data in a preprocess hook directly from a controller, but I'm guessing there has to be some way I can render the product_group node and get the variables that are available in hook_preprocess_node. Am I correct, and if so, how do I do it?

Was it helpful?

Solution

So the problem turned out to be an incorrect #theme template name in my returned render array. The node type I was adding content to was called product_group, but in my controller, I returned this:

 return [
   '#theme' => 'node__product_resource__full',
   '#product_group' => $content,
   '#node' => $pg_node,
   '#view_mode' => 'full',
 ];

product_resource is a valid content type in the site. Once I changed it to

'#theme' => 'node__product_group__full',

It worked fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top