passing a parameter from a content type to a module

被刻印的时光 ゝ 提交于 2019-12-13 21:59:01

问题


I assumed this would be easy but I am stumped.

I have a custom content type that includes an id field. I render these with a basic page template.

I have written a small module that creates a block which is populated with data from an external API. Everything works except I cannot seem to figure out how to pass the value of the id from the content of a given page to my module so it can make the API call.

It would be a couple of lines of code in straight php, it can't be that complicated in Drupal 8 and twig can it?


回答1:


I managed to find a solution here

I am re-posting it in case it is useful to anyone else.

If you are generating a custom block you can access content fields via the routing system inside your block build function like this:

public function build() {

    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $field_my_custom_value = $node->field_my_custom_value->value;
    }

    //do something with the variable, like make the API call

    //Make sure to set the cache to the context or even to zero if you need
    return array(
      '#markup' => $this->t('my content to render'),
      '#cache' => array(
         'contexts' => ['contexts' => ['route']],
      ),
   );
}



回答2:


I think you can reach what you want with a HOOK_preprocess.

use:

YOUR_MODULE_preprocess_node(&$variables){ ... } or
YOUR_MODULE_preprocess_block(&$variables){ ... }

to access your variable from the content type and pass it to your function oder template.



来源:https://stackoverflow.com/questions/37946419/passing-a-parameter-from-a-content-type-to-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!