Skip to content

Instantly share code, notes, and snippets.

@manojiksula
Last active August 7, 2023 07:01
Show Gist options
  • Save manojiksula/d26bc389035d402d71a854cbcc258309 to your computer and use it in GitHub Desktop.
Save manojiksula/d26bc389035d402d71a854cbcc258309 to your computer and use it in GitHub Desktop.

#Logger

\Drupal::logger('logger1')->error('<pre>'.print_r($e->getMessage(), TRUE).'</pre>');

Override strings which is defined in core (messages from drupal_set_message or form field markup)

For example:
To replace the text "Password reset instructions will be sent to your registered email address." in core/modules/user/src/Form/UserPasswordForm.php

Make following change in settings.php

$settings['locale_custom_strings_en'][''] = [
  'Password reset instructions will be sent to your registered email address.' => 'You are not able to log in. If you need to reset your password, please confirm by clicking Submit',
];

Load Taxonomy Term by ID

$termID = 1;

$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termID);

$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($termID);

Get Taxonomy in Custom Block via URL

$termID = "";
$route = \Drupal::routeMatch();
if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
	$termID = $route->getRawParameter('taxonomy_term');
}

Get Taxonomy Tree

$vid = 'contact_country';                      
$terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree($vid);


$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, 0, null, true);

Get all vocabularies in drupal 8 & 9

Use Drupal\taxonomy\Entity\Vocabulary;

$vocabularies = Vocabulary::loadMultiple();

// To get names:
foreach($vocabularies as $voc) {
  dump($voc->label()); // etc
}

Get a list of translated taxonomy terms in Drupal 8

$vocabulary = 'MY_VOCABULARY_NAME';
$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary);
$query->sort('weight');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
$termList = array();

foreach($terms as $term) {
    if($term->hasTranslation($language)){
        $tid = $term->id();
        $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
        $termList[$tid] = $translated_term->getName();
    }
}

// To print a list of translated terms. 
foreach($termList as $tid => $name) {
     print $name;
}

Load term by name

$term_name = 'Term Name';
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties(['name' => $term_name]);


 /**
   * Utility: find term by name and vid.
   * @param null $name
   *  Term name
   * @param null $vid
   *  Term vid
   * @return int
   *  Term id or 0 if none.
   */
  protected function getTidByName($name = NULL, $vid = NULL) {
    $properties = [];
    if (!empty($name)) {
      $properties['name'] = $name;
    }
    if (!empty($vid)) {
      $properties['vid'] = $vid;
    }
    $terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties($properties);
    $term = reset($terms);

    return !empty($term) ? $term->id() : 0;
  }

Delete Nodes

$result = \Drupal::entityQuery("node")
->condition('created', strtotime('-1 days'), '>=')
->execute();
$storage_handler = \Drupal::entityTypeManager()->getStorage("node");
$entities = $storage_handler->loadMultiple($result);
$storage_handler->delete($entities);

Delete Taxonomy

$group_vocab = 'dop_group';
$segment_vocab = 'change_language';

$this->delete_terms_from_vocab($group_vocab);
$this->delete_terms_from_vocab($segment_vocab);


function delete_terms_from_vocab($vid) {
	$tids = \Drupal::entityQuery('taxonomy_term')
	->condition('vid', $vid)
	->execute();

	if (empty($tids)) {
		return;
	}

	$term_storage = \Drupal::entityTypeManager()
	->getStorage('taxonomy_term');
	$entities = $term_storage->loadMultiple($tids);

	$term_storage->delete($entities);
}

get entity reference field from depedent taxonomy programmatically

$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($termID);
$groups = $term->get('field_dop_group')->referencedEntities();
foreach ($groups as $group) {
	$title = $group->label();
}

Downgrade or Reset install hook version for updb install file

drush php-eval "echo drupal_set_installed_schema_version('sggs_dop', '9000');"
../../../vendor/bin/drush php-eval "echo drupal_set_installed_schema_version('sggs_dop', '9003');"

Messenger service (@messenger)

use Drupal\Core\Messenger\MessengerInterface;

/**
 * The Messenger service.
 *
 * @var \Drupal\Core\Messenger\MessengerInterface
 */
protected $messenger;

/**
 * MyModuleService constructor.
 *
 * @param \Drupal\Core\Messenger\MessengerInterface $messenger
 *   The messenger service.
 */
public function __construct(MessengerInterface $messenger) {
  $this->messenger = $messenger;
}


// Add message (defaults to "status" message type).
$this->messenger->addMessage('Hello world');

// Add specific type of message.
$this->messenger->addMessage('Hello world', 'custom');
$this->messenger->addError('Hello world');
$this->messenger->addStatus('Hello world');
$this->messenger->addWarning('Hello world');

// Retrieve and remove specific type of message.
$this->messenger->deleteByType('error');

// Retrieve specific type of message, without removing it.
$this->messenger->messagesByType('error');

// Retrieve and remove all messages.
$messages = $this->messenger->deleteAll();

// Retrieve all messages, without removing them.
$messages = $this->messenger->all();

Form Ajax Callback

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('OK'),
  '#button_type' => 'primary',
  '#ajax' => [
    'callback' => [$this, 'promptCallback'],
    'wrapper' => 'box-container',
  ],
];

$form['show_error'] = [
  '#type' => 'markup',
  '#markup' => '<div id="result-message"></div>', // inside this div message will be added 
];

public function promptCallback(array &$form, FormStateInterface $form_state) {
  \Drupal::messenger()->addError($errorMessage);
  $message = [
    '#theme' => 'status_messages',
    '#message_list' => \Drupal::messenger()->all(),
  ];
  \Drupal::messenger()->deleteAll();
  $messages = \Drupal::service('renderer')->render($message);
  $response = new AjaxResponse();
  $response->addCommand(new HtmlCommand('#result-message', $messages));
  return $response;
}

Copy All Block from One Theme to another Theme in Drupal 9

$block_ids = \Drupal::entityQuery('block')->condition('theme', 'sg2')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);
  $new_id = str_replace('sg2', 'sgbg_cz', $parent_block->get('id'));
  $new_parent_block = \Drupal\block\Entity\Block::load($new_id);
  if(is_null($new_parent_block)) {
  $child_block = $parent_block->createDuplicateBlock($new_id, 'sgbg_cz');
    // @TODO: set other properties that might need to be unique to this new theme's block
    $child_block->save();
  }

}

Delete Disabled Block from specific theme

$block_ids = \Drupal::entityQuery('block')->condition('theme', 'sg2')->execute();
foreach ($block_ids as $block_id) {
  $parent_block = \Drupal\block\Entity\Block::load($block_id);
  if($parent_block->get('status') === false) {
    $parent_block->delete();
  }
}

Get a url/route and params from request

If you have the url for example /page?uid=123&num=452

// To get all params, use: 

$param = \Drupal::request()->query->all();

// To get "uid" from the url, use:

$uid = \Drupal::request()->query->get('uid');

// To get "num" from the url, use:

$num = \Drupal::request()->query->get('num');

// To get the base url -> O/P https://www.local.com
$host = \Drupal::request()->getSchemeAndHttpHost();   

$current_url = Url::fromRoute('<current>');
$path = $current_url->toString();

//Examples for the page /en/user/login:
$current_url->toString();    // /en/user/login
$current_url->getInternalPath();    // user/login
$path = $current_url->getRouteName();   // <current>

//Drupal syntax.
$path = \Drupal::request()->attributes->get('_system_path');

// Include a query string
$current_uri = \Drupal::request()->getRequestUri();

// For the current raw path (the un-aliased Drupal path):
$current_path = \Drupal::service('path.current')->getPath();
$result = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);

//Get the url of the request for displayed on the browser.
$page = \Drupal::request()->getRequestUri();

//To get the current path Route
$current_path = \Drupal::service('path.current')->getPath();
$getRoute = \Drupal::routeMatch()->getRouteName();


To get the current route name, use:
$route_name = \Drupal::routeMatch()->getRouteName();

or

$current_route_name = \Drupal::service('current_route_match')->getRouteName();

// To check if the current page is a taxonomy term use:
if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
    $term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}

// To check if the current page is a node, node preview or node revision use:
$route_match = \Drupal::routeMatch();
if ($route_match->getRouteName() == 'entity.node.canonical') {
    $node = $route_match->getParameter('node');
}
elseif ($route_match->getRouteName() == 'entity.node.revision') {
    $revision_id = $route_match->getParameter('node_revision');
    $node = node_revision_load($revision_id);
}
elseif ($route_match->getRouteName() == 'entity.node.preview') {
    $node = $route_match->getParameter('node_preview');
}


// To check if the current page is a contact form page use:
if (\Drupal::routeMatch()->getRouteName() == 'entity.contact_form.canonical') {
    //  contact form
    $contact_form = \Drupal::routeMatch()->getParameter('contact_form');
}

//To check if the current page is a view page use:
$current_route_name = \Drupal::service('current_route_match')->getRouteName();

Custom Cache

public function getData() {
  $options = [];
    $cacheId = 'cacheId';
    $dataCached = \Drupal::cache()->get($cacheId);
    if (!$dataCached) {
      
      $expire = \Drupal::time()->getRequestTime() + (36000);
      $database = \Drupal::database();
      $results = $query->execute()->fetchAll();

      $options = [];
      foreach ($results as $dropdown) {
        $options[$dropdown->dropdown_id] = $dropdown->default_product;
      }

      \Drupal::cache()->set($cacheId, $options, $expire);
    }
    else {
      $options = $dataCached->data;
    }
  }
  return $options;
}
@Pooja04
Copy link

Pooja04 commented Oct 19, 2022

Override strings which is defined in core

(messages from drupal_set_message or form field markup)

For example:
To replace the text "Password reset instructions will be sent to your registered email address." in core/modules/user/src/Form/UserPasswordForm.php

Make following change in settings.php

$settings['locale_custom_strings_en'][''] = [
  'Password reset instructions will be sent to your registered email address.' => 'You are not able to log in. If you need to reset your password, please confirm by clicking Submit',
];

Load entity node by nid

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

Get all languages enabled

$langcodes = \Drupal::languageManager()->getLanguages();
$langcodeslist = array_keys($langcodes);

Get alias for the path with translation

$alias = \Drupal::service('path_alias.manager')->getAliasByPath('node/5', 'en'); // Output: /welcome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment