في Drupal 7 ، إذا كنت أرغب في الحصول على معرف العقدة للعقدة المعروضة حاليًا (على سبيل المثال node/145
) يمكنني الحصول عليها باستخدام الدالة arg()
في هذه الحالة ترجع arg(1)
145.
كيف يمكنني تحقيق نفس الشيء في Drupal 8؟
سيتم إلغاء المعلمة من nid إلى كائن العقدة الكاملة بحلول الوقت الذي يمكنك الوصول إليه ، لذلك:
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// You can get nid and anything else you need from the node object.
$nid = $node->id();
}
انظر سجل التغيير لمزيد من المعلومات.
من الصحيح استخدام \Drupal::routeMatch()->getParameter('node')
. إذا كنت تحتاج فقط إلى معرف العقدة ، فيمكنك استخدام \Drupal::routeMatch()->getRawParameter('node')
.
ملاحظة في صفحة معاينة العقدة ، لا يعمل ما يلي:
$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->id();
لصفحة معاينة العقدة ، يجب عليك تحميل العقدة بهذه الطريقة:
$node = \Drupal::routeMatch()->getParameter('node_preview');
$nid = $node->id();
إذا كنت تستخدم أو تنشئ كتلة مخصصة ، فعليك اتباع هذا الرمز للحصول على معرف عقدة url الحالي.
// add libraries
use Drupal\Core\Cache\Cache;
// code to get nid
$node = \Drupal::routeMatch()->getParameter('node');
$node->id() // get current node id (current url node id)
// for cache
public function getCacheTags() {
//With this when your node change your block will rebuild
if ($node = \Drupal::routeMatch()->getParameter('node')) {
//if there is node add its cachetag
return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
} else {
//Return default tags instead.
return parent::getCacheTags();
}
}
public function getCacheContexts() {
//if you depends on \Drupal::routeMatch()
//you must set context of this block with 'route' context tag.
//Every new route this block will rebuild
return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
}