php

Issue: https://www.drupal.org/project/drupal/issues/953034

my_module.module
<?php

use Drupal\views\Plugin\Block\ViewsBlock;

/**
 * Implements hook_block_alter().
 */
function hook_block_alter(array &$definitions) {
  foreach ($definitions as $block_id => &$block_definition) {
    if ($block_definition['class'] === ViewsBlock::class) {
      $block_definition['class'] = 'Drupal\my_module\Plugin\Block\ViewsBlock';
    }
  }
}

ViewsBlock.php
<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\views\Plugin\Block\ViewsBlock as ViewsBlockCore;

/**
 * Replaces the generic Views block.
 */
class ViewsBlock extends ViewsBlockCore {

  /**
   * {@inheritdoc}
   */
  public function build() {
    if (empty($this->view->result) && empty($this->view->empty)) {
      // Without caching.
      // return ['#cache' => ['max-age' => 0]];
      // With hard caching.
      return [];
    }

    return parent::build();
  }

}

Example for a single datetime field

my_single_datetime_field.php
use Drupal\Core\Datetime\DrupalDateTime;

/** @var Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');

// Get DateTime object from stored date from a DateTimeFieldItemList field.
$my_date = $node->field_my_date->date;

// Get unix timestamp.
$my_date_timestamp = $my_date->getTimestamp();

// For formatting your DateTime object all other arguments are optional:
// See DateFormatterInterface for built-in options, or use machine name of a date format in config.
$type = 'medium';
// Custom PHP date format if $type="custom".
$format = '';

$formatted = $date_formatter->format($my_date_timestamp, $type, $format, $timezone = NULL, $langcode = NULL);

 

Example for a daterange field

my_datetime_range_field.php
use Drupal\Core\Datetime\DrupalDateTime;

/** @var Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
$date_formatter = \Drupal::service('date.formatter');

// Get DateTime objects from stored date from a DateTimeFieldItemList field.
$start_date = $node->field_my_date->start_date;
$end_date = $node->field_my_date->end_date;

// For formatting your DateTime object all other arguments are optional:
// See DateFormatterInterface for built-in options, or use machine name of a date format in config.
$type = 'medium';
// Custom PHP date format if $type="custom".
$format = '';

$start_date_formatted = $date_formatter->format($start_date, $type, $format, $timezone = NULL, $langcode = NULL);
$end_date_formatted = $date_formatter->format($end_date, $type, $format, $timezone = NULL, $langcode = NULL);
YodaNotation.php
// The rookie mistake with one =.
if ($variable = 42) {
    // This will print 42 not because the if statement is true but because $variable gets overridden.
     print($variable);
}

// This will return an error.
if (42 = $variable) {
    // This will not be executed.
    print($variable);
}

if ($variable == 42) {
    // This will print 42 because the if statement is true and $variable is not overridden.
    print($variable);
}

// This works just fine.
if (42 == $variable) {
    // It will be the same outcome as the one directly above.
    print($variable);
}
24.05.2024 | Lothar Ferreira Neumann

Yoda notation

Enable nested arrays in $form_states with:

tree.php
$form['my_text']['#tree'] = TRUE;

Here in an example code:

alter_structure.php
$form['my_text'] = [
  '#type' => 'details',
  '#title' => t('Text'),
  '#open' => TRUE,
  // Without this line you cannot access nested arrays.
  '#tree' => TRUE,
];

$default_value = '';
$form['my_text']['text'] = [
  '#type' => 'textfield',
  '#title' => t('Text to appear as the page.'),
  '#description' => t('If textfield is left empty no text will be displayed page'),
  '#default_value' => $default_value,
];
17.07.2025 | Lothar Ferreira Neumann

How to enable nested array structure in $form_states

entity_field_value.php
// For single value fields.
$entity->field_name->value;

// If you don`t know the main property.
$main_property_name = $entity->field_name->getMainPropertyName();

// For multiple value fields.
$entity->field_name->getValue();
12.02.2026 | Michael Ebert

Get value of an entity field

array_shuffle.php
$array = [
  'key_one' => 'one',
  'key_two' => 'two',
  'key_three' => 'three',
];
onlyKeys.php
// You will get a mixed array with only keys or values, depends if you use array_flip()

// Change keys to values and vice versa.
array_flip($array);

// Reduce the array to the keys and shuffle them.
array_rand($array);
shuffledArray.php
// Array will be shuffled with key => value staying a pair.

// Shuffle the key => value array, keeping both.
shuffle($array);
04.04.2024 | Lothar Ferreira Neumann

Mix values of an associated array

default_date_value.php
public static function getDefaultDate() {
  $end_date = new DrupalDateTime();
  $end_date->setTime(23, 59, 59);
  $timezone = new DateTimeZone('UTC');
  $end_date->setTimezone($timezone);
  return $end_date->format('Y-m-d\TH:i:s');
}

field.field.node.mycontenttype.field_date.yml
default_value_callback: '\Drupal\my_custom_module\Entity\DefaultDateValue::getDefaultDate'

downcastArray.php
$array = [
  'key_one' => 'one',
  'key_two' => 'two',
  'key_three' => 'three',
];

// Downcast associated array to indicated array with only keys.
array_keys($array);

// Downcast associated array to indicated array with only values.
array_values($array);
ExampleOutcome.txt
Outcome array_keys():
$array = [
  [0] = 'key_one',
  [1] = 'key_two',
  [2] = 'key_three',
];

Outcome array_values():
$array = [
  [0] = 'one',
  [1] = 'two',
  [2] = 'three',
];
04.04.2024 | Lothar Ferreira Neumann

Downcast an array.

custom_module.install
<?php

/**
 * Update node title of all nodes.
 */
function custom_module_update_10001(&$sandbox) {
  // Define you entity type.
  $entity_type = 'node';

  // Load the entity type manager service.
  $entity_type_manager = \Drupal::service('entity_type.manager');

  // Get the storage for the entity type.
  $entity_storage = $entity_type_manager->getStorage($entity_type);

  if (!isset($sandbox['total'])) {
    $all_entity_ids = $entity_storage->getQuery()
      ->accessCheck()
      ->execute();
    $sandbox['total'] = count($all_entity_ids);
    $sandbox['current'] = 0;

    if (empty($sandbox['total'])) {
      $sandbox['#finished'] = 1;
      return;
    }
  }

  $entities_per_batch = 25;
  $entity_ids = $entity_storage->getQuery()
    ->accessCheck()
    ->range($sandbox['current'], $entities_per_batch)
    ->execute();
  if (empty($entity_ids)) {
    $sandbox['#finished'] = 1;
    return;
  }

  // Optionally, perform operations with the loaded entities.
  // For example, load and modify each node and set a new title.
  foreach ($entity_ids as $entity_id) {
    $entity = $entity_storage->load($entity_id);

    if ($entity->hasField('title')) {
      $entity->setTitle('New Title');
    }

    $entity->save();
    $sandbox['current']++;
  }

  \Drupal::messenger()
    ->addMessage($sandbox['current'] . ' users processed.');

  if ($sandbox['current'] >= $sandbox['total']) {
    $sandbox['#finished'] = 1;
  }
  else {
    $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  }

}
21.05.2026 | Michael Ebert

Do bulk updates as a batch job