drupal8snip

كتابات: 





IMPORTANT NOTE: These snippets is a direct snippets. Please make sure to use dependency injection always to make sure to follow the standards and to make your code testable later on.
// 20190110
// Drupal 8 generate uuid.
$uuid = \Drupal::service('uuid')->generate();

// Drupal form clean values array.
$values = $form_state->cleanValues()->getValues('');

// Getting node author uid.
$node->getOwnerId();

// Checks whether a string appears to be in the format of a UUID.
use Drupal\Component\Uuid\Uuid;
Uuid::isValid($uuid_to_validate);

// Install new drupal 8 necessary contrib modules.
composer require drupal/admin_toolbar drupal/adminimal_theme drupal/rename_admin_paths

// Published constant value.
NodeInterface::PUBLISHED
NodeInterface::PROMOTED
NodeInterface::STICKY
NodeInterface::NOT_PUBLISHED
NodeInterface::NOT_PROMOTED
NodeInterface::NOT_STICKY

// Install Drupal console.
composer require drupal/console --optimize-autoloader
// Views hook orders:
// Source: https://www.drupal.org/project/views/issues/1329438#comment-13020162
views_plugins
views_data
views_data_alter
views_plugins_alter
views_default_views_alter
views_pre_view
views_pre_build
views_query_alter
views_query_substitutions
views_post_build
views_pre_execute
views_post_execute
views_pre_render
views_post_render
// Views hooks preprocess execution order.
// Source: https://drupal.stackexchange.com/a/180714/24113
hook_preprocess_views_view
hook_preprocess_views_view_field
hook_preprocess_views_view_fields
hook_preprocess_views_view_grid
hook_preprocess_views_view_table
hook_preprocess_views_view_unformatted
hook_preprocess_views_view_list
// howto change your drupal HTML markup to not be like the default Drupal website.
// Add this line to your settings.php file. (MAKE SURE YOU ARE DOING THIS NOT ON A LIVE WEBSITE)
// This line will change /sites/default/files folder and make it /uploads.
$settings['file_public_path'] = 'uploads';

// You may want to remove Generator meta tag.
https://drupal.stackexchange.com/a/226781
// drupal 8 load term by custom field
$term = current(\Drupal::entityTypeManager()->getStorage('taxonomy_term')
  ->loadByProperties(['field_CUSTOM_NAME' => 'THE_VALUE', 'vid' => 'VOCABULARY_MACHINE_NAME'])
);

// Load term by tid.
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
// Drupal 8 fetch taxonomy term custom field from term object.
print $term->get('field_CUSTOM_NAME')->getValue()[0]['value'];
print $term->get('tid')->getValue()[0]['value'];
print $term->get('vid')->getValue()[0]['target_id'];
print term->get('name')->getValue()[0]['value'];
// Taxonomy term save multiple values.
$VALUES = $term->get('field_CUSTOM_NAME')->getValue();
$VALUES[]['value'] = 'NEW VALUE';
$term->field_CUSTOM_NAME->setValue($VALUES);
// Drupal 8 save and get load cookie.
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
$SymfonyResponse = new Response();
$cookie = new Cookie('YOUR_COOKIE_KEY', 'VALUE_HERE_PLEASE', 0, '/' , NULL, FALSE);
$SymfonyResponse->headers->setCookie($cookie);
$SymfonyResponse->send();

// Load cookie.
$request_cookie = \Drupal::request()->cookies->all();
print $request_cookie['YOUR_COOKIE_KEY'];
// Drupal 8 get user IP.
$current_ip = \Drupal::request()->getClientIp();
// Drupal8 save node programmatically.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'TITLE_HERE',
  'field_category' => [
    'target_id' => 'TID'
  ],
]);
$node->save();
// 20190115
// Drupal 8 read request headers for current user request and get header values.
use Symfony\Component\HttpFoundation\ServerBag;
$headers = new ServerBag($_SERVER);
$headers = $headers->getHeaders();
print_r($headers);
  // Drupal 8 load nodes by custom Taxonomy field.
  $nodes = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(['type' => 'CONTENT_TYPE', 'field_CUSTOM_TERM_REF_FIELD' => $tid]);
// Drupal8 load all nodes from a specific content type.
$nids = \Drupal::entityQuery('node')->condition('type','CONTENT_TYPE')->execute();
$nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);
// 20190308 Bali
// Loading current user details.
$user = User::load(\Drupal::currentUser()->id());
// 20190308
// Getting and load nodes related to a specific user using entityQuery.
  $query = \Drupal::entityQuery('node')
    ->condition('status', 1) //published or not
    ->condition('type', 'CONTENT_TYPE') //content type
    ->condition('uid', \Drupal::currentUser()->id()) //content type
    ->pager(10); //specify results to return
  $nids = $query->execute();

  // Using entityTypeManager.
  $nodes = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadByProperties(['type' => 'CONTENT_TYPE', 'uid' => \Drupal::currentUser()->id()]);
// 20190308
// Load file URL from file field value.
  $fid = $entity->get('field_IMAGE')->getValue()[0]['target_id'];
  $file = \Drupal\file\Entity\File::load($fid);
  $image_url = $file->url();
  // $image_url = file_create_url($file->getFileUri());

// Getting styled URL from drupal 8 custom image field.
  $fid = $entity->get('field_IMAGE')->getValue()[0]['target_id'];
  $file = \Drupal\file\Entity\File::load($fid);
  $image_uri = $file->getFileUri();
  $styled_url = ImageStyle::load('large')->buildUrl($image_uri);
// 20190617
// Page cache can not be controlled by max-age or contexts for anyonymous. You can prevent that kind of caching by using this method to avoid caching for the page or prevent caching in forms.
// Source: https://drupal.stackexchange.com/a/219583/24113
\Drupal::service('page_cache_kill_switch')->trigger();
// 20190619
// Save user programmatically.
    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $new_user = User::create();
    // Mandatory.
    $new_user->setPassword('PASSWORD_AS_TEXT');
    $new_user->enforceIsNew();
    $new_user->setEmail('[email protected]');
    $new_user->setUsername('USER_NAME');
    // Optional.
    $new_user->set('init', '[email protected]');
    $new_user->set('langcode', $language);
    $new_user->set('preferred_langcode', $language);
    $new_user->set('preferred_admin_langcode', $language);
    $new_user->addRole('ROLE_NAME');
    // Set out custom values.
    $new_user->set('field_CUSTOM', 'VALUE');
    $new_user->activate();

    _user_mail_notify('register_no_approval_required', $new_user);
    user_login_finalize($new_user);
    \Drupal::messenger()->addStatus($this->t('Registration successful. You are now logged in.'));
    $form_state->setRedirect('');
// 20190619
// Load user by specific custom field.
$id_number_check = \Drupal::entityQuery('user')
      ->condition('status', 1)
      // ->condition('roles', 'ROLE_NAME')
      // ->condition('roles',['ROLE_NAME_1', 'ROLE_NAME_2'], 'IN')
      // ->condition('status', 1)
      // ->sort('uid', 'ASC')
      // ->range(0, 1)
      ->condition('field_NAME', 'VALUE')
      ->execute();
// 20190626
// Save taxonomy programmatically.
  use Drupal\taxonomy\Entity\Term;
  $term = Term::create([
    'name' => 'test',
    'vid' => 'client',
  ]);
  $term->save();
  print $term->id();
// 20190702
// Since `format_date` is deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.

    // using Drupal time service.
    $time_value = \Drupal::time()->getCurrentTime();
    print \Drupal::service('date.formatter')->format($time_value, 'long');

    // Using DrupalDateTime class.
    use Drupal\Core\Datetime\DrupalDateTime;

    // Getting site default timezone value.
    $timezone = Drupal::config('system.date')->get('timezone')['default'];
    // User default timezone is: drupal_get_user_timezone().
    // Instead of time() use this next line.
    $time_value = \Drupal::time()->getCurrentTime();
    $date_original = DrupalDateTime::createFromTimestamp($time_value, $timezone);
    print $date_original->getTimestamp();
    print $date_original->format('Y-m-d\TH:i:s');

// Drupal 8 strtotime
$timezone = Drupal::config('system.date')->get('timezone')['default'];
$time_value = \Drupal::time()->getCurrentTime();
$date_original = DrupalDateTime::createFromTimestamp($time_value, $timezone);
print strtotime('+1 day', $date_original->getTimestamp());
// 20190703
// Generate URL as HTML in Drupal 8
// Always it's better to use fromRoute() instead of fromUri() to make sure to include the language prefix in the URL.
$register_link_from_uri = render(Link::fromTextAndUrl('Register', Url::fromUri('base:user/register', ['attributes' => ['class' => 'extra-link-register']]))->toRenderable());
$register_link_from_route = render(Link::fromTextAndUrl('Register', Url::fromRoute('user.register', [], ['attributes' => ['class' => ['extra-link-register']]]))->toRenderable());
$password_link_from_route = render(Link::fromTextAndUrl(t('Reset your password'), Url::fromRoute('user.pass', [], ['attributes' => ['class' => ['extra-link-reset-password']]]))->toRenderable());
print $password_link_from_route; // Will print HTML code of rendered link.

// Form redirect to a view route.
    $url = Url::fromRoute('view.VIEW_MACHINE_NAME.DISPLAY_MACHINE_NAME', [
      'node' => $node->id(),
    ]);
    $form_state->setRedirectUrl($url);

// New request link going to node 1 view page :)
$add_new = render(Link::fromTextAndUrl(t('New request'), Url::fromRoute('entity.node.canonical', ['node' => 1], [
  'attributes' => [
    'class' => [
      'button',
      'button--primary',
    ],
  ],
]))->toRenderable());
// 20190715
// Getting content moderation state value.
$moderation_state = $node->get('moderation_state')->getValue();
$moderation_state = $moderation_state[0]['value'];
// 20190715
// Redirect to a specific route.
    $url = Url::fromRoute('view.VIEW_MACHINE_NAME.DISPLAY_MACHINE_NAME', [
      'node' => $node->id(),
    ])->toString();
    $response = new RedirectResponse($url);
    $response->send();

// Getting the URL as plain text full URL
    $url = Url::fromRoute('view.VIEW_MACHINE_NAME.DISPLAY_MACHINE_NAME', [
      'node' => $node->id(),
    ], ['absolute' => TRUE])->toString();
// 20190715
// Load all referenced entities from a multi valued field.
// For example this is a reference field to taxonomy terms.
// https://gorannikolovski.com/blog/how-loop-through-referenced-entities
$node->get('field_NAME')->referencedEntities();
// 20190715
// Alter view fields output.
/**
 * Implements hook_views_pre_render().
 */
function HOOK_views_pre_render(ViewExecutable $view) {
  if (($view->id() == 'VIEW_NAME') && ($view->current_display == 'DISPLAY_NAME')) {
    foreach ($view->result as $key => &$row) {
      print_r(json_decode(json_encode($row)));
      print $row->_entity->id();
      // Fetch the entities from the relationship.
      foreach ($row->_relationship_entities as $entity) {
        print $entity->id();
      }

      // Exit to view field keys extracted from $row.
      exit;
      // Alter view field.
      $row->node_field_data_title = 'TEST TITLE VALUE';
    }
  }
}
// 20190715
// Drupal 8 alter nothing field in views. Alter views fields before output.
/**
 * Implements template_preprocess_views_view_fields().
 */
function MODULENAME_preprocess_views_view_field(&$vars) {
  // Print all available fields.
  foreach ($vars['view']->field as $key => $field) {
    // We will print the field name.
    print $key . '<HR>';
  }
  exit;

  // To access current row entity.
  $entity = $vars['row']->_entity;
  $entity_id = $entity->id();

  // To access entities from relationship.
  $entities = $vars['row']->_relationship_entities;

  // When you find your field key use this code below.
  if(isset($vars['view']) && ($vars['view']->id() == 'VIEW_MACHINE_NAME') && ($vars['view']->current_display == 'DISPLAY_MACHINE_NAME')) {
    if (isset($vars['view']->field) && (count($vars['view']->field) > 0)) {
      // if ($vars['field']->field == 'YOUR_FIELD_NAME')
      if ($vars['field']->field == 'nothing') {
        $vars['output'] = 'TEST_CUSTOM_VALUE';
      }
    }
  }
}
// 20190717
// Render image as HTML. Render img as HTML output.
$file_id = '1111';
$image_file = \Drupal\file\Entity\File::load($file_id);
$image_uri = $image_file->getFileUri();
$build = [
  '#theme' => 'image_style',
  '#style_name' => 'thumbnail',
  '#uri' => $image_uri,
];
/** @var \Drupal\Core\Render\Renderer $renderer */
$renderer = \Drupal::service('renderer');
$img_html = $renderer->render($build);
print $img_html;
// Drupal 8 Remove title from the node view. Remove any field from a specific rendered node view mode.
// You can also override the display options by using getComponent() and setComponent() from EntityDisplayBase class.
/**
 * Implements hook_entity_view_display_alter().
 */
function MODULENAME_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context) {
  if (isset($context['entity_type']) && ($context['entity_type'] == 'node')
  && isset($context['bundle']) && ($context['bundle'] == 'CONTENT_TYPE')
  && isset($context['view_mode']) && ($context['view_mode'] == 'VIEW_MODE')) { // teaser, full ..
    $display->removeComponent('title');
    $display->removeComponent('field_NAME');

    // Still, I'm trying to remove only the title link :)
    // keywords: drupal 8 remove link from title field display link_to_entity.
  }
}
// 20190718
// Load paragraph entity from node object.
if ($node->field_PARAGRAPH_FIELD) {
  foreach ($node->field_PARAGRAPH_FIELD as $item) {
    $paragraph = Paragraph::load($item->target_id);
  }
}
// Force using specific form view mode.
/**
 * Implements hook_entity_type_alter().
 */
function MODULENAME_entity_form_display_alter(&$form_display, $context) {
  // Check the specific content type that we are targeting.
  if (isset($context['entity_type']) && isset($context['bundle'])
    && ($context['entity_type'] == 'node') && ($context['bundle'] == 'CONTENT_TYPE_MACHINE_NAME')) {
    // Get the current user.
    $user = \Drupal::currentUser();
    // Force our custom view mode if the current user is not having this permission.
    if (!$user->hasPermission('CUSTOM PERMISSION')) {
      $storage = \Drupal::service('entity_type.manager')->getStorage('entity_form_display');
      $form_display = $storage->load('node.CONTENT_TYPE_MACHINE_NAME.VIEW_MODE_MACHINE_NAME');
    }
  }

  // Force using a specific view mode in user form if user does not have a specific permission.
  if (isset($context['entity_type']) && isset($context['bundle'])
    && ($context['entity_type'] == 'user') && ($context['bundle'] == 'user')) {
    // Get the current user.
    $user = \Drupal::currentUser();
    // Force our custom view mode if the current user is not developer.
    if (!$user->hasPermission('CUSTOM PERMISSION')) {
      $storage = \Drupal::service('entity_type.manager')->getStorage('entity_form_display');
      $form_display = $storage->load('user.user.VIEW_MODE_MACHINE_NAME');
    }
  }
}
// 20190721
// Force a specific view mode on entity display page.
/**
 * Implements hook_entity_view_mode_alter().
 */
function MODULENAME_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  // Check the specific entity type that we are targeting.
  if (($entity->getEntityTypeId() == 'user') && ($entity->bundle() == 'user') && ($view_mode == 'full')) {
    // Get the current user.
    $user = \Drupal::currentUser();
    // Force our custom view mode if the current user does not have a specific permission.
    if (!$user->hasPermission('PERMISSION NAME')) {
      // Make sure to enable the (compact) view mode of the user from /admin/config/people/accounts/display
      $view_mode = 'compact';
    }
  }

  // Same code but for specific content type.
  if (($entity->getEntityTypeId() == 'node') && ($entity->bundle() == 'CONTENT_TYPE_MACHINE_NAME') && ($view_mode == 'full')) {
  }
}
// drupal 8 alter view mode field value.
// Create a virtual field when display an entity.
/**
 * Implements hook_entity_view_alter().
 */
function MODULENAME_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  if (($display->getTargetEntityTypeId() == 'node') && ($display->getTargetBundle() == 'CONTENT_TYPE_MACHINE_NAME') && ($display->getOriginalMode() == 'VIEW_MODE')) {
    $build['field_virtual'] = [
      '#markup' => 'HEEEY!',
      '#weight' => 99,
    ];
  }
  // Check if this is our targeted view.
  if (($display->getOriginalId() == 'user.user.full') && ($display->getEntityTypeId() == 'entity_view_display')) {
    print $display->getOriginalId();
    print '<HR>';
    print $display->getTargetEntityTypeId();
    print '<HR>';
    print $display->getOriginalMode();
    print '<HR>';
    print $display->getEntityTypeId();
    print '<HR>';
    print $display->getTargetBundle();
    exit;
  }
}
// 20190728
// Update node and save it as a new revision.
$node->set('field_test', $value);
// Making sure to save this update as a new revision.
$node->setNewRevision(TRUE);
$node->revision_log = 'write_log_message_here';
$node->setRevisionCreationTime(REQUEST_TIME);
$node->setRevisionUserId(\Drupal::currentUser()->id());
$node->save();
// 20190730
// drupal 8 template_preprocess_views_view alter row markup.

// 20190731
// Tempstore.
// Source: http://karimboudjema.com/en/drupal/20190315/saving-temporary-values-form-private-tempstore-drupal-8
tempstore.private
// 1. Get the private tempstore factory, inject this in your form, controller or service.
$tempstore = \Drupal::service('tempstore.private');
// Get the store collection. 
$store = $tempstore->get('my_module_collection');
// Set the key/value pair.
$store->set('key_name', $value);

// 2. Get the value somewhere else in the app.
$tempstore = \Drupal::service('tempstore.private');
// Get the store collection. 
$store = $tempstore->get('my_module_collection');
// Get the key/value pair.
$value = $store->get('key_name');

// Delete the entry. Not mandatory since the data will be removed after a week.
$store->delete('key_name');

// --
// Deprecated services
$tempstore = \Drupal::service('user.private_tempstore')->get('my_module_name');
$tempstore = \Drupal::service('tempstore.shared')->get('my_module_name');
// Source: https://www.drupal.org/node/2935639
// 20190820
// Get paragraph field type (file) file_extensions from field instance.
$field_instance = \Drupal::entityTypeManager()->getStorage('field_config')->load('paragraph.PARAGRAPH_TYPE_NAME.field_NAME');
$settings = $field_instance->getSettings();
print $settings['file_extensions'];
// 20190829
// Auto import languages.
// Add these two lines to your module .info file.
'interface translation project': MODULE_NAME
'interface translation server pattern': modules/custom/MODULE_NAME/translations/%project-%language.po
// The .po file should be exists inside your module.
// Don't miss to configure your Import behavior on:  /admin/config/regional/translate/settings
// Import from UI: /admin/reports/translations
// Drush command:
// drush locale-check && drush locale-update && drush cr
// @NOTE: It is not a good idea to do this if you are working on your contrib module since the translation files should be on a separate folder. (Thanks mhmd Gomma)
// For more info please review these two lines:
https://git.drupalcode.org/project/drupal/blob/8.8.x/core/modules/locale/locale.api.php#L30
https://git.drupalcode.org/project/drupal/blob/8.8.x/core/modules/locale/locale.api.php#L55
// 20190829
// Get site name $site_name
$site_name = Drupal::config('system.site')->get('name');
print $site_name;
// 20190924
// Delete field programmatically.
use Drupal\field\Entity\FieldStorageConfig;
$field = FieldStorageConfig::loadByName('taxonomy_term', 'field_tr_title');
if ($field) {
  // Delete this field.
  $field->delete();
}
else {
  // The field can not be loaded or maybe it does not exist.
}
// 20191010
// Invalidate cached rendered context.
Cache::invalidateTags(['rendered']);

فضلاً إذا أعجبتك هذه الصفحة لاتنسى أن تقوم بمشاركتها