Skip to content

Instantly share code, notes, and snippets.

@raphaellarrinaga
Last active September 4, 2022 21:49
Show Gist options
  • Save raphaellarrinaga/0f9c654915ce1cf94464eae596e22a30 to your computer and use it in GitHub Desktop.
Save raphaellarrinaga/0f9c654915ce1cf94464eae596e22a30 to your computer and use it in GitHub Desktop.
[Drupal 8 php/config cheatsheet] #tags: drupal8, php, config, cheatsheet

Drupal 8 PHP cheatsheet

Get current node id

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $nid = $node->id();
}

Load media entity & get a field

use Drupal\media\Entity\Media;

$media = Media::load($nid);
$file_uri = $media->field_media_file->entity->getFileUri();

How can I programmatically display a block?

@see https://drupal.stackexchange.com/questions/171686/how-can-i-programmatically-display-a-block

Content Blocks

$bid = ??? // Get the block id through config, SQL or some other means
$block = \Drupal\block_content\Entity\BlockContent::load($bid);
$render = \Drupal::entityTypeManager()->
  getViewBuilder('block_content')->view($block);
return $render;

Plugin blocks

$block_manager = \Drupal::service('plugin.manager.block');
// You can hard code configuration or you load from settings.
$config = [];
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// Some blocks might implement access check.
$access_result = $plugin_block->access(\Drupal::currentUser());
// Return empty render array if user doesn't have access.
// $access_result can be boolean or an AccessResult class
if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
  // You might need to add some cache tags/contexts.
  return [];
}
$render = $plugin_block->build();
// In some cases, you need to add the cache tags/context depending on
// the block implemention. As it's possible to add the cache tags and
// contexts in the render method and in ::getCacheTags and 
// ::getCacheContexts methods.
return $render;

Config entities

$block = \Drupal\block\Entity\Block::load('config.id');
$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);
return $render;

Fast site install with lando & config management

$ lando drush site-install standard --account-name=admin --account-pass=admin --db-url='mysql://drupal8:drupal8@database/drupal8' --site-name=Test site
# Get uuid from source
$ drush config-get "system.site" uuid
# @see https://drupal.stackexchange.com/questions/150481/how-can-i-import-the-configuration-on-a-different-site/217126
# Set local uuid
$ drush config-set "system.site" uuid "fjfj34-e3bb-2ab8-4d21-9100-b5etgetgd99d5"

Import drupal 8 configuration into a fresh install website

$ drush cget system.site uuid
'system.site:uuid': bfb11978-d1a3-4eda-91fb-45decf134e25
$ drush cset system.site uuid bfb11978-d1a3-4eda-91fb-45decf134e25
$ drush ev '\Drupal::entityManager()->getStorage("shortcut_set")->load("default")->delete();'

@see https://www.dannyenglander.com/blog/drupal-8-development-how-import-existing-site-configuration-new-site

Testing

@todo description

~/Sites/siteName ᐅ vendor/bin/dcr web/themes/contrib/file
phpcs --standard=Drupal dir/file
phpcbf --standard=Drupal dir/file
~/Sites/siteName/web ᐅ eslint dir/file.js

Links

@see https://agaric.coop/blog/creating-links-code-drupal-8

use Drupal\Core\Link;
$link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' => 1]);

More flexibility with URL object

use Drupal\Core\Link;
use Drupal\Core\Url;
$link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' => 1]));

Internal links which have no routes

$link = Link::fromTextAndUrl('This is a link', Url::fromUri('base:robots.txt'));

External links:

  use Drupal\Core\Url;
  use Drupal\Core\Link;
  $link = !empty($url) ? Link::fromTextAndUrl($this->t('Newsletter'), Url::fromUri($url, [
    'attributes' => [
      'target' => '_blank',
      'class' => ['button']
    ],
  ])) : '';
  $html_link = $link->toString();

Using the data provided by a user

$link = Link::fromTextAndUrl('This is a link', Url::fromUserInput('/node/1');

Linking entities.

$link = Link::fromTextAndUrl('This is a link', Url::fromUri('entity:node/1'));

Drupal usually expects a render array if you are going to print the link, so the Link object has a method for that

$link->toRenderable();

Add links inside a t() method. Need to pass the link as a string.

$link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' => 1]));
$this->t('You can click this %link' ['%link' => $link->toString()]);

Render images with image styles

@source https://www.webomelette.com/how-render-your-images-image-styles-drupal-8

URL only

$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl('public://my-image.png');

Render image

$render = [
  '#theme' => 'image_style',
  '#style_name' => 'thumbnail',
  '#uri' => 'public://my-image.png',
  // optional parameters
];

Example

@todo to be refined.

if ($paragraph && $paragraph->hasField('field_image') && !$paragraph->get('field_image')->isEmpty()) {
  $entity_img_id = $paragraph->get('field_image')->first()->getValue()['target_id'];
  $image = \Drupal::entityTypeManager()->getStorage('file')->load($entity_img_id);
  $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
  $uri = $style->buildUrl($image->getFileUri());

  return [
    '#theme' => 'image',
    '#style_name' => 'thumbnail',
    '#uri' => $uri,
  ];
}

Responsive image

$file = $paragraph->get('field_image')->entity;

if ($file) {
  $image = \Drupal::service('image.factory')->get($file->getFileUri());

  $logo_build = [
    '#theme' => 'responsive_image',
    '#responsive_image_style_id' => 'promoted_teaser',
    '#uri' => $file->getFileUri(),
  ];

  // Add the file entity to the cache dependencies.
  // This will clear our cache when this entity updates.
  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($logo_build, $file);

  $build['#image_p'.$paragraph_counter] = $logo_build;
}

Rewrite the output of a field

$variables["items"][0]["content"] = "";

Provide frontpage variant

try {
  $isFront = \Drupal::service('path.matcher')->isFrontPage();
}
catch (Exception $e) {
  $isFront = FALSE;
}

Rendering fields

$node->field_my_thing->get(0)->view();

$node->field_my_thing->view();

$node->field_my_thing->view('teaser');

$node->field_my_thing->view([
  'type' => 'image',
  'label' => 'hidden',
  'settings' => array(
    'image_style' => 'larger_thumbnail',
    'image_link' => 'content',
  ),
]);

@see https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet @see Long answer https://www.computerminds.co.uk/articles/rendering-drupal-8-fields-right-way

Unlock bloqued used

drush uublk username to unblock the user

@see https://www.drupal.org/node/1023440

Get entity reference field (taxonomy) value

$termId = $relationshipEntities['profile']->get('field_job_title')->target_id;
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termId);
$termValue = $term->get('field_public')->value;

Set block class for custom block bundles.

@see https://www.drupal.org/node/2724333

/**
 * Implements hook_preprocess_block().
 */

function hops_preprocess_block(&$variables) {
  // Add class for a specific block id.
  $block_id = $variables['elements']['#id'];
  switch ($block_id) {
    case '':
      $variables['attributes']['class'][] = '';
      break;

    default:
      break;
  }

  if (isset($variables['elements']['content']['#block_content'])) {
    $variables['attributes']['class'][] = 'block--'. $variables['elements']['content']['#block_content']->bundle();
  }
}

Render a profile view

  $uid = $variables['user']->id();
  $args = [$uid];
  $view = \Drupal\views\Views::getView('profiles');
  if (is_object($view)) {
    $view->setArguments($args);
    $view->setDisplay('user_view');
    $view->preExecute();
    $view->execute();

    // @see https://drupal.stackexchange.com/questions/219475/get-result-view-with-formatter-programmattically
    $profileFields = [];
    foreach ($view->result as $rid => $row) {
      foreach ($view->field as $fid => $field ) {
        $profileFields[$rid][$fid . '-value'] = $field->getValue($row);
        $profileFields[$rid][$fid . '-render'] = $field->render($row);
        $profileFields[$rid][$fid] = $field->advancedRender($row);
      }
    }
    $variables['profileFields'] = $profileFields;
  }

Render a node

On drupal 8 every elements (almost) are an entity, as any entity you can render a node.

@see http://www.drupal8.ovh/en/tutoriels/339/render-a-node-or-an-entity

$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';
$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$node = $storage->load($nid);
$build = $view_builder->view($node, $view_mode);
$output = render($build);
// Note : you can also use if you don't want to use different entity types.
$node = Node::load($nid);

Get node field value from html scope

function hook_preprocess_html(&$variables) {
  // If current page is a node full page. 
  $node = \Drupal::request()->attributes->get('node');
  if ($node) {
    // Get entity reference field entities and loop.
    $node_paragraphs = $node->get('field_paragraphs')->referencedEntities();

    foreach ($node_paragraphs as $entity) {
      // Check entity type and for a not empty field.
      if ($entity->getType() === "card" && !($entity->get('field_media')->isEmpty())) {
        // Add body class.
        $variables['attributes']['class'][] = "has-intro-banner";
      }
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment