PHP

Caching Data

Caching Data

Here's a simple way to cache data if the item itself has a lot of logic that bogs the server down...

Let's say you run a batch process and build a catalog item for an e-comm store.

Your 'foreach' would be converted into a batch process, but for sake of explaining caching here, we'll assume that a 'foreach' loop wouldn't timeout. :)

foreach ($products as $product) {
	// Again, do not use a foreach for large data sets.
	generateProductTile($product);
}

/**
 * Generates product tiles with a lot of logic behind how they are displayed
 */
function generateProductTile($product) {
	$drupalCache = \Drupal::cache();
	$cid = 'my_module:product_tile: . ' $product->id;
	// If we've already cached this result, we don't have to do any
	// excessive processing.
	if ($cached = $drupalCache->get($cid)) {
		if (!empty($cached)) {
			return $cached->data;
		}
	}
	
	// If we don't have a cache object, we do whatever we need to build the output.
	$title = $product->label();
	$price = $product->price();
	
	// Maybe we add some logic to the price, and this process is pretty intensive.
	$price = change_price($price);
	
	// Maybe we need to get an image... e-comm entities have weird ways of storing images
	// so this may also take a while.
	$image = get_product_image($product);
	
	// Let's pretend we're done... now we can render this tile.
	$themedTile = [
		'#theme' => 'product_tile',
		'#data' => [
			'title' => $title,
			'price' => $price,
			'image' => $image
		]
	];
	
	$rendererService = \Drupal::service('renderer');
	// This is just a basic way to render the basic html for this item
	// based on a hook_theme entry.
	$renderedTile = rendererService->renderRoot($themedTile);
	
	// Now that we did all that work, lets cache it so if we run this again
	// we don't have to do all that logic again. We can just gather pre-rendered tiles.
	// Setting the tag implies that when you save or update a product entity
	// this cache will be invalidated and rebuild itself the next time it's called.
	// (Double check the tag format for the entity)
	$drupalCache->set(cid: $cid, data: $renderedTile, tags: ['product:' . $product->id()]);
	
	// In the ->set method, you can set the expiration as well. By default it is 'permanent'
	// If you want some other caching policy, do that.
	
	// Since we want the built item, return it.
	return $renderedTile;
}

As an added bonus, here's the hook_theme  in the .module file, and the twig format to render this.

<?php

/**
 * Implements hook_theme().
 */
 function MY_MODULE_theme() {
 	return [
 		'product_tile' => [
 			'variables' => ['data' => NULL],
 			'template' => 'product_tile' /* This assumes the file is in the /templates directory within your module */
 		]
 	];
 }

And your twig file in MY_MODULE/templates directory.

** the image could also be pre-rendered, but this is more to show how you can use parts of variables as data within your twig file.

<h1>{{ data.title }}</h1>
<div class="price">{{ data.price }}</div>
<img src="{{ data.image.src }}" alt="{{ data.image.alt }}">

Get Image From Media Entity

Get Image From Media Entity

Using the media library is a great way to manage images (and other assets really) that may be used multiple times across your site, or even may need to be updated globally.

Programmatically referencing them can be a pain... Here's a simple function that can be used to grab from an image field in a media entity. This will give you the url and the alt properties so you can use them in a template file.

 

// Get the media ID from a field within your node or any other entity
if (!$entity->hasField('field_node_image')) {
	if (!$entity->get('field_node_image')->isEmpty()) {
		$mediaEntityId = $entity->get('field_node_image')->getValue()[0]['target_id'];
		$imageData = getMediaFieldImage($mediaEntityId);
	}
}

function getMediaFieldImage($mediaId) {
	// Use dependency injection as suggested.
    $entityTypeManager = \Drupal::entityTypeManager();
    $loggerFactory = \Drupal::logger('my_module');
    
    // Set a default... 
    $mediaImage = ['url' => '', 'alt' => ''];
    
    // Use a try catch because it fails a bit more gracefully.
    try {
      $media = $entityTypeManager->getStorage('media')->load($mediaId);
      // Get the field instances of type image
      $fieldDefinitions = $media->getFieldDefinitions();
    } catch (\Exception $e) {
      $loggerFactory->error('Error loading media: @error', ['@error' => $e->getMessage()]);
      return $mediaImage;
    }
    $imageField = FALSE;
    
    // This is really assuming that you have a single 'image' field on the media entity.
    // You could also get any other 'type' you want.
    foreach ($fieldDefinitions as $field) {
      if ($field->getType() == 'image') {
        $imageField = $field->getName();
        // If you want to do multiple images... well, change it up.
        break;
      }
    }
    if ($imageField) {
      // Now that we know the field to get data from, we get the field
      // data just like on any other entity.
      $image = $media->get($imageField)->getValue();
      if(!empty($image)) {
        try {
          $fid = $image[0]['target_id'];
          $file = $entityTypeManager->getStorage('file')->load($fid);
          if ($file) {
            $mediaImage['url'] = $file->createFileUrl();
            $mediaImage['alt'] = $image[0]['alt'];
          }
        } catch (\Exception $e) {
          $loggerFactory->error('Error loading file: @error', ['@error' => $e->getMessage()]);
        }
      }
    }
    return $mediaImage;

  }

 

Entity Reference Selection

Entity Reference Selection

To 'alter' what shows in an entity reference selection

Reference https://drupal.stackexchange.com/questions/298105/can-i-create-non-default-entityreferenceselection

In src/Plugin/EntityReferenceSelection

<?php

namespace Drupal\YOUR_MODULE\Plugin\EntityReferenceSelection;

use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;

/**
 * Provides a query for a node entity reference selection.
 *
 * @EntityReferenceSelection(
 *   id = "YOUR_MODULE_REFERENCE_SELECTION_ID",
 *   label = @Translation("Filter nodes with a specific field value."),
 *   entity_types = {"node"},
 *   group = "YOUR_MODULE_REFERENCE_SELECTION_GROUP",
 *   weight = 1
 * )
 */
class YourModuleEntityReferenceSelection extends NodeSelection {
  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityQuery($match, $match_operator);
    $query->condition('field_featured', 1', '=');
    return $query;
  }
}

Set Message with a link as an argument

Set Message with a link as an argument

Need to output a message with a link in the text?

$link = Link::createFromRoute('Link Title', 'my_module.my_route', [
          'argument' => 'argument value',
        ]);
        
        $m_args = ['%message_link' => $link->toString()];
        
        \Drupal::messenger()->addStatus(t('Here is a message, and here is a link. %message_link', $m_args));

Output Twig Values in console.log

Output Twig Values in console.log

Trying to debug twig? Not rendering? Try this from within your twig file...

<script>console.log({{ _context | json_encode | raw}});</script>

 

Create a simple service

Create a simple service

Also includes dependency injection

MY_MODULE.services.yml

services:
  my_module.cool_service:
    class: Drupal\my_module\Services\CoolService
    arguments: ['@logger.factory']

/src/Services/CoolService.php

<?php

namespace Drupal\my_module\Services;

use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * CoolService returns what you give it in an array.
 */
class CoolService {


  /**
   * Logger Factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $loggerFactory;


  /**
   * Constructs the Cool service.
   *
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerFactory
   *   A Guzzle client object.
   */
  public function __construct(LoggerChannelFactoryInterface $loggerFactory) {
    $this->loggerFactory = $loggerFactory->get('my_module');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.factory')
    );
  }

  public function doSomething($someData) {
    $output = [
      'my_data' => $someData;
    ];

    $this->loggerFactory->error('Lets log a message!');
    
    return $output;
  }


}

Calling the service

$coolService = \Drupal::service('my_module.cool_service');

$returnedData = $coolService->doSomething('My Data');

echo $returnedData;

 

Update field values in multiple paragraphs

Update field values in multiple paragraphs

Let's say you have a LOT of paragraphs on your site. (Meaning Drupal Paragraphs contributed module entities).

Now you want to update a field in all of them. Rather than trying to find each and every one within nodes, you can run a simple script to update a field value.

This will simply load all paragraphs of a specific bundle. Then for each one, you update a value then save.

If you have a lot of paragraphs, you may want to run a batch process.

// Load all the paragraph entities of type
$entityManager = \Drupal::entityTypeManager();
$entities = $entityManager
    ->getStorage('paragraph')
    ->loadByProperties(['type' => 'MY_PARAGRAPH_TYPE','status' => 1]);

// Looping through each one and changing a value
// This could/should be set up in a batch process for a lot of items
foreach($entities as $key => $entity) {
    $paragraphStorage = $entityManager->getStorage('paragraph');
    $paragraph = $paragraphStorage->load($key);
    $paragraph->set('field_my_field','MY_NEW_VALUE');
    $paragraph->save();
}

 

Correct Timezone Handling

Correct Timezone Handling

Sometimes when outputting a Drupal date field, it will display in UTC, not in your desired timezone.

You can run the date through a few lines of code to output as desired.

$dt = new \DateTime($date[0]['value'], new \DateTimeZone('UTC'));
$dt->setTimeZone(new \DateTimeZone('America/Los_Angeles'));
$correct_date =  $dt->format('Y-m-d H:i:s');