首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法使令牌替换正常工作

无法使令牌替换正常工作
EN

Drupal用户
提问于 2020-05-21 13:53:14
回答 2查看 2.7K关注 0票数 0

我几乎有这个确切的例子,但因为它适用于Drupal 8:将令牌替换值存储在数据库中,而不是标记本身)。

我有一个内容类型“文章”,其中有一个“body”字段,该字段已经通过令牌筛选模块填充了令牌。我认为代码应该类似于在这里找到的https://www.drupal.org/project/drupal/issues/2043055,但不能让它工作。

代码语言:javascript
运行
复制
function MYMODULE_node_presave(Drupal\Core\Entity\EntityInterface $node) {
  if ($node->bundle() == 'article') {
    $body = $node->get('body')->value;
    $token = Drupal::token();
    $body = $token->replace($body);
  }
}

谢谢你的考虑,-c

EN

回答 2

Drupal用户

回答已采纳

发布于 2020-05-27 02:07:56

虽然我无法实际用数据库中令牌的数据替换令牌,但我还是找到了在电子邮件中替换令牌的最终目标。这是基本代码(在https://www.drupal.org/forum/support/module-development-and-code-questions/2020-05-03/add-save-send-email-button-to-both#comment-13647867上有更多详细信息)。

代码语言:javascript
运行
复制
$node = \Drupal\node\Entity\Node::load($nid);  //load the current node
$token_service = \Drupal::token();  //get the Drupal token service which replaces tokens with tokens' data
$body_field_data = $node->get('body')->value;  //get the "text" (basic data) of the body field
$token_data = array(  //assigns the current node data to the 'node' key in the $data array; the node key is recognized by the Token service
  'node' => $node,
);
$token_options = ['clear' => TRUE];  //part of the Token replacement service; A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated
$params['body'] = $token_service->replace($body_field_data, $token_data, $token_options);  //sets the 'body' key of the $params array equal to the basic body field data plus replaces the tokens in the body field```
票数 3
EN

Drupal用户

发布于 2020-05-21 18:53:10

您需要在主体上设置新值,并保存它。

代码语言:javascript
运行
复制
function MYMODULE_node_presave(Drupal\Core\Entity\EntityInterface $node) {
  if ($node->bundle() == 'article') {
    $body = $node->get('body')->value;
    $token = Drupal::token();
    $body = $token->replace($body);
    $node->set('body', $body);
  }
}
票数 0
EN
页面原文内容由Drupal提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://drupal.stackexchange.com/questions/293871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档