Drupal8 常用API

Submitted by admin on Tue, 11/05/2019 - 10:18
##获取当前用户$current_user = \Drupal::currentUser();$user = \Drupal\user\Entity\User::load($current_user->id());// or just$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

entity query

$query = \Drupal::entityQuery('node');$query->condition('status', 1);$query->condition('type', 'MY_NODE_TYPE');$query->condition('langcode', $language()->getId());$ids = $query->execute();$media = \Drupal::entityTypeManager()          ->getListBuilder('media')          ->getStorage()          ->loadByProperties([            'bundle' => 'media_bundle_name',            'status' => 1,        ]);##参考https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3AentityQuery/8.2.xhttps://www.drupal.org/node/2849874

语言

Language can be obtained from other node, i.e.:$language = $node->language();or language manager:$language = \Drupal::languageManager()->getCurrentLanguage();

timer

use Drupal\Component\Utility\Timer;  
Timer::start('xx');  
sleep(1);  
dpm(Timer::read('xx'));

模块相关

判断模块是否启用

\Drupal::moduleHandler()->moduleExists('gin_toolbar'); 

获取当前theme

$active_theme = \Drupal::service('theme.manager')->getActiveTheme();

$active_theme_name = $active_theme->getName();

获取host

$host = \Drupal::request()->getSchemeAndHttpHost(); $host = \Drupal::request()->getHost();