Drupal 8 code snippets

Enable debug mode via settings.php

  1. $conf['block_cache'] = FALSE;
  2. $conf['page_compression'] = FALSE;
  3. $conf['cache_lifetime'] = 0;
  4. $conf['page_cache_maximum_age'] = 0;
  5. $conf['page_cache_invoke_hooks'] = TRUE;
  6. $conf['preprocess_css'] = FALSE;
  7. $conf['preprocess_js'] = FALSE;
  8. $settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';
  9. $config['system.performance']['css']['preprocess'] = FALSE;
  10. $config['system.performance']['js']['preprocess'] = FALSE;
  11. $settings['cache']['bins']['render'] = 'cache.backend.null';
  12. $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';
  13. $settings['extension_discovery_scan_tests'] = TRUE;
  14.  
  15. $settings['system.logging']['error_level'] = 'all';
  16.  
  17. ini_set('display_errors', TRUE);
  18. ini_set('display_startup_errors', TRUE);


Module and theme development

 

Get current path

 
  1. $path = \Drupal::service('path.current')->getPath(); or $current_uri = \Drupal::request()->getRequestUri();
 

Get alias

 
  1. $path = \Drupal::service('path.current')->getPath();
  2. $alias = \Drupal::service('path.alias_manager')->getAliasByPath($path);

Get current user

 
  1. $user = \Drupal::currentUser(); or $user = User::load(\Drupal::currentUser()->id());
 

Get entity field


  1. $entity->get('field_name')->getValue();
  2. // or
  3. $node->get('field_machine_name')->getString();

Redirect

  1. $response = new RedirectResponse($path);
  2. $response->send();

Entity query

  1. //Get published nodes:
  2. $node_query = \Drupal::entityQuery('node');
  3. //or
  4. $node_query = \Drupal::service('entity.query');
  5. ->condition('type', 'article')
  6. ->condition('status', 1)
  7. ->execute();
  8.  
  9. // Get users by role
  10. $user_query = $query->get('user')
  11. ->condition('roles', 'user_role', 'CONTAINS')
  12. ->execute();