manniru
2/24/2016 - 5:08 PM

Drupal 8 snippets

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>