我几乎有这个确切的例子,但因为它适用于Drupal 8:将令牌替换值存储在数据库中,而不是标记本身)。
我有一个内容类型“文章”,其中有一个“body”字段,该字段已经通过令牌筛选模块填充了令牌。我认为代码应该类似于在这里找到的https://www.drupal.org/project/drupal/issues/2043055,但不能让它工作。
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
发布于 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上有更多详细信息)。
$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```发布于 2020-05-21 18:53:10
您需要在主体上设置新值,并保存它。
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);
}
}https://drupal.stackexchange.com/questions/293871
复制相似问题