โปรดทราบว่าคำตอบที่ได้รับการยอมรับนั้นใช้กับหน่วยงานโหนดโดยเฉพาะ แต่หน่วยงานทั้งหมดมีชุดข้อมูล เอนทิตีจำนวนมากเช่นuser
หรือmenu_link_content
(สำหรับลิงก์เมนูที่กำหนดเอง) มีเพียงหนึ่งบันเดิลซึ่งสอดคล้องกับประเภทเอนทิตีเอง
entity_type.bundle.info
บริการดำเนินการโดยDrupal \ หลัก \ Entity \ EntityTypeBundleInfoให้การเข้าถึงข้อมูลกำนิติบุคคล วิธีการgetAllBundleInfo()
และgetBundleInfo($entity_type_id)
ส่งกลับอาร์เรย์คีย์ตามประเภทเอนทิตีและชื่อเครื่องบันเดิลตามลำดับด้วยอดีตนั้นมีอาร์เรย์ของบันเดิลคีย์โดยชื่อเครื่องบันเดิล แต่ละบันเดิลมีlabel
คีย์พร้อมชื่อที่จำง่ายของบันเดิลที่แปล
ด้านล่างนี้เป็นตัวอย่างที่แสดงความแตกต่างระหว่างชื่อเครื่องเอนทิตีเนื้อหาฉลากชื่อเครื่องบันเดิลและป้ายกำกับบันเดิล รหัสสันนิษฐานว่ามีอย่างน้อยหนึ่งในการเชื่อมโยงเมนูที่กำหนดเองที่มี ID 1
ของ นอกจากนี้ยังถือว่ามีarticle
ชนิดของโหน (มัด) ว่ามีอย่างน้อยหนึ่งโหนดที่มี ID ของ1
และที่โหนดเป็นประเภทโหนด article
(มัด)
<?php
$entity_type_manager = \Drupal::entityTypeManager();
$bundle_info = \Drupal::service("entity_type.bundle.info")->getAllBundleInfo();
$current_user = \Drupal::currentUser()->getAccount();
// Prints "user".
print $current_user->getEntityTypeId() . PHP_EOL;
// Prints "User".
print $current_user->getEntityType()->getLabel() . PHP_EOL;
// Prints "user".
print $current_user->bundle() . PHP_EOL;
// Prints "User".
print $bundle_info[$current_user->getEntityTypeId()][$current_user->bundle()]['label'] . PHP_EOL;
$my_menu_link = $entity_type_manager->getStorage('menu_link_content')->load(1);
// Prints "menu_link_content".
print $my_menu_link->getEntityTypeId() . PHP_EOL;
// Prints "Custom menu link".
print $my_menu_link->getEntityType()->getLabel() . PHP_EOL;
// Prints "menu_link_content".
print $my_menu_link->bundle() . PHP_EOL;
// Prints "Custom menu link".
print $bundle_info[$my_menu_link->getEntityTypeId()][$my_menu_link->bundle()]['label'] . PHP_EOL;
$my_article = $entity_type_manager->getStorage('node')->load(1);
// Prints "node".
print $my_article->getEntityTypeId() . PHP_EOL;
// Prints "Content".
print $my_article->getEntityType()->getLabel() . PHP_EOL;
// Prints "article".
print $my_article->bundle() . PHP_EOL;
// Prints "Article".
print $bundle_info[$my_article->getEntityTypeId()][$my_article->bundle()]['label'] . PHP_EOL;
ตรวจสอบให้แน่ใจว่าใช้การฉีดพึ่งพาที่เป็นไปได้ในรหัสของคุณแทนที่จะอาศัยวิธีคงที่ของDrupal
ชั้นเรียน