Skip to content

Instantly share code, notes, and snippets.

@mgalang
Last active June 17, 2022 13:58
Show Gist options
  • Save mgalang/360ee286d70c1b57b2db to your computer and use it in GitHub Desktop.
Save mgalang/360ee286d70c1b57b2db to your computer and use it in GitHub Desktop.
Drupal 8 snippets

Create link from text and url

$url = Url::fromRoute($route_name);
$link = Link::fromTextAndUrl($text, $url);

Create link from route

$link = Link::createFromRoute('Link Text', 'route_name')->getUrl();

Disable page caching

\Drupal::service('page_cache_kill_switch')->trigger();

Sanitize url

UrlHelper::stripDangerousProtocols($url);

Sanitize string for css use

$css_class = Html::cleanCssIdentifier('css_identifier');

Custom validation for widget

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'path' && isset($element['alias'])) {
    $element['alias']['#element_validate'] = array('_mymodule_field_widget_validate_element');
  }
}

function _mymdule_field_widget_validate_element(array &$element, FormStateInterface $form_state) {
  $value = rtrim(trim($element['#value']), " \\/");
  if (!empty($value)) {
    // Validate stuff and throw error
    // $form_state->setError($element, t('some error'));
  }
}

Get current active link

$active_link = \Drupal::service('menu.active_trail')->getActiveLink();

Load a Term entity

use Drupal\taxonomy\Entity\Term;
Term::load($id);

Load all terms from vocabulary

$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree($vocabulary);

Load entity through entity storage (optional cache clear)

$storage = \Drupal::service('entity_type.manager')
  ->getStorage('storage_type');
$storage->resetCache();
$entity = $storage->load($entity_id);

Load entity by UUID

$entity = \Drupal::service('entity.repository')
    ->loadEntityByUuid($bundle, $uuid);

Enable module

\Drupal::service('module_installer')->install(array('my_module'));

How to print variable keys in twig (and not running out of memory)

<ol>
    {% for key, value in _context  %}
      <li>{{ key }}</li>
    {% endfor %}
</ol>

Entity reference field definition in custom entity

$fields['reference'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Entity reference'))
      ->setDescription(t('Entity reference'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'entity_type')
      ->setSetting('handler', 'default')
      ->setDisplayOptions('form', [
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => [
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ],
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment