【发布时间】:2018-11-01 15:43:46
【问题描述】:
我为 Drupal 8 创建了一个自定义模块。我创建了一个钩子,用于检测何时创建新节点,然后向订阅者发送通知。我的代码是这样的:
<?php
/**
* @file
* Contains onesignal_api.module.
*
*/
use Drupal\Core\Entity\EntityInterface;
/***
* Hook into OneSignal API to send push notifications once a new node is created
*/
function onesignal_api_insert(\Drupal\Core\Entity\EntityInterface $node) {
if($node->isNew()) {
function sendMessage() {
$content = array(
"en" => 'New Node Created'
);
$hashes_array = array();
array_push($hashes_array, array(
"id" => "like-button",
"text" => "Like",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "http://push-test/"
));
array_push($hashes_array, array(
"id" => "like-button-2",
"text" => "Like2",
"icon" => "http://i.imgur.com/N8SN8ZS.png",
"url" => "http://push-test/"
));
$fields = array(
'app_id' => "XXXXXXXXX",
'include_player_ids' => array("XXXXXX","XXXXX","XXXXXX"),
'data' => array(
"foo" => "bar"
),
'contents' => $content,
'web_buttons' => $hashes_array
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Authorization: Basic XXXXXXX'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode($return);
$data = json_decode($response, true);
print_r($data);
$id = $data['id'];
print_r($id);
print("\n\nJSON received:\n");
print($return);
print("\n");
}//if Node is new
}//func hook signal
我需要进行一些更改才能使其正常工作吗? if 语句中的所有代码都可以在 if 语句之外运行。
【问题讨论】:
-
hook_node_insert 是在实体保存到数据库之后调用的,这就是您的
isNew()检查失败的原因。另一方面,您不需要在hook_node_insert' anyways because that hook only executes AFTER THE FIRST TIME an entity is saved to the database. So you can be sure this is a newly created node everytime inhook_node_insert 中检查该条件。' -
嗯嗯好的。创建节点时是否有一个? @coderodour
-
那将是
hook_node_submit,这是在将节点保存在数据库中之前拥有所有可用于操作的值的理想位置。 -
drupal 8 @coderodour 似乎已弃用它
-
hook_entity_presave 是另一种选择,看看它是否符合您的需求。
标签: php drupal hook drupal-modules drupal-8