php

get_all_contrib_modules.php
<?php

/**
 * Get a list of all contrib modules.
 * 
 @param string $context
 *   The context of the module like contrib, custom or core.
 *   Only the parameter 'contrib', 'custom', or 'core' are 
 *   available parameters.
 * @return array
 *   Returns an array with all contrib modules' machine names.
 */
public function getAvailableModules(string $context): array {
  $context = 'contrib';
  $module_list = \Drupal::service('module_handler')->getModuleList();
  $modules = [];

  foreach ($module_list as $module) {
    if (str_contains($module->getPath(), 'contrib')) {
      $modules[$module->getName()] = $module;
    }
  }

  return $modules;
}
error_handling.php
<?php

$error_message = t('There is an error with this.');

\Drupal::messenger()->addError($error_message));
\Drupal::logger('my_module')->log('error', $error_message);
getBundlesWithViewmode.php
  private function getBundlesWithViewmode(string $entity_type, string $view_mode): array {
    $bundles = [];

    foreach (\Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type) as $bundle => $info) {
      $view_modes = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle($entity_type, $bundle);
      if (isset($view_modes[$view_mode])) {
        $bundles[] = $bundle;
      }
    }

    return $bundles;
  }
  
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