Drupal cheat sheets

Collection of some nice helper Drupal code examples that I need to use from time to time. Decided to put this stuff here because I constantly forget them ;)

Nested array which you need to use for select form element

Lots of time you have nested array like this

$plugins = array(
  'plugin_1' => array('title' => 'Plugin 1', ....),
  'plugin_2' => array('title' => 'Plugin 2', ....),

and you need select element with plugin key and title:

$form['select_plugin'] = array(
  '#type' => 'select',
  '#title' => t('Select plugin'),
  '#options' => array('' => t('Select plugin')) + array_map(function ($array) { return $array['title']; }, $plugins),

How to render just one field from your entity

For example image field with thumbnail style:

$display = array(
  'label' => 'hidden',
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail',
    'image_link' => '',
$wrapper = entity_metadata_wrapper('your_entity', $your_entity);
$image = field_view_value('your_entity', $your_entity, 'your_entity_field_picture_name', $wrapper->your_entity_field_picture_name->value(), $display);

How to reset Drupal 8 user password

You forgot your password and drush is not working, but you have access to files on server, then no problem:

# User ID 1 for root user.
$admin_user = entity_load('user', 1);

You can put this code in index.php or where it fits you better.