วิธีการตรวจสอบว่าหน้าปัจจุบันเป็นข้อผิดพลาด 404 จากโมดูล / แม่แบบ?


20

วิธีการตรวจสอบใน D7 หากหน้าปัจจุบันจะกลับข้อผิดพลาด 404 จากโมดูล / แม่แบบ?


1
คำถามที่เกี่ยวข้องกับ Drupal 6: drupal.stackexchange.com/questions/10259/ …
mpdonadio

ยังเกี่ยวข้องกับdrupal.stackexchange.com/questions/327/ …
mikeytown2

คำตอบ:


33

ใน Drupal 7 drupal_get_http_header()คุณสามารถใช้

ในไฟล์ template.php ให้ใช้รหัสนี้

$status = drupal_get_http_header("status");
if ($status === '404 Not Found'){
  // Do something.
}

ใน Drupal 8 คุณสามารถใช้รหัสต่อไปนี้ใน hook

$route_name = \Drupal::request()->attributes->get('_route');
if ('system.404' === $route_name) {
  // Do something.
}

ฟังก์ชั่นนี้ใช้โค้ดอะไรใน template.php
Jordan Magnuson

1
คุณสามารถวางรหัสนี้ไว้ใน template_preprocess_page (& $ ตัวแปร)
fzmaster

นอกจากนี้ยังสามารถนำมาใช้ใน hook_exit ()
sheldonkreger

หากคุณต้องการจัดการกับ 403 คุณสามารถใช้:if ($status == '403 Forbidden') { /* ... do stuff ... */ }
tyler.frankenstein

2
หมายเหตุ: การแก้ปัญหาสำหรับ Drupal 8 ขึ้นอยู่กับsystem.404เส้นทางไม่ทำงานถ้าคุณได้ระบุไว้หน้าโหนดเป็นหน้า 404 ในการกำหนดค่า> ระบบ> การตั้งค่าพื้นฐานเว็บไซต์ ดูที่ @Gervase 'คำตอบสำหรับโซลูชันที่ใช้งานได้เมื่อคุณมีหรือไม่มีหน้า 404 ที่กำหนดเอง
JamesWilson

11

Drupal 8.2.x:

น่าเสียดายที่ drupal_get_http_header ("สถานะ") ไม่ทำงานอีกต่อไป

ลอง:

$status = \Drupal::requestStack()->getCurrentRequest()->attributes->get('exception');
if ($status && $status->getStatusCode() == 404){

}

มีการสนทนาเกี่ยวกับเรื่องนี้ที่นี่: https://www.drupal.org/node/1969270


1
นี่คือสิ่งที่ฉันกำลังมองหา! <3
JamesWilson

1
แต่ระวัง - วัตถุที่ถูกเรียกใช้ซ้ำอาจไม่มีgetStatusCodeฟังก์ชั่น
fritzmg

มันจบการค้นหาที่ไม่รู้จบและพยายามของฉัน
usmanjutt84

4

นี่เป็นวิธีที่ง่ายที่สุดในการตรวจหาการเข้าถึงถูกปฏิเสธ (403) และ Page Not Found (404) ใน Drupal 7

// get the menu router item for the current page
$router_item = menu_get_item();

// if there is no router item, this page is not found
$is_page_not_found_404 = empty($router_item);

// if 'access' is empty for the router item, access is denied
$is_access_denied_403 = empty($router_item['access']);

$router_itemจะไม่ว่างเปล่าหากsite_404ตัวแปรถูกตั้งค่าเป็นเส้นทางของโหนดดังนั้นจึงจำเป็นต้องมีการตรวจสอบเพิ่มเติม
gapple

menu_get_item สายแพงไปหน่อยต่อหน้าใช่ไหม
เควิน
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.