#Logger
\Drupal::logger('logger1')->error('<pre>'.print_r($e->getMessage(), TRUE).'</pre>');
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',
];
$termID = 1;
$term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($termID);
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($termID);
$termID = "";
$route = \Drupal::routeMatch();
if ($route->getRouteName() == 'entity.taxonomy_term.canonical') {
$termID = $route->getRawParameter('taxonomy_term');
}
$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);
Use Drupal\taxonomy\Entity\Vocabulary;
$vocabularies = Vocabulary::loadMultiple();
// To get names:
foreach($vocabularies as $voc) {
dump($voc->label()); // etc
}
$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;
}
$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;
}
$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);
$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);
}
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($termID);
$groups = $term->get('field_dop_group')->referencedEntities();
foreach ($groups as $group) {
$title = $group->label();
}
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');"
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['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;
}
$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();
}
}
$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();
}
}
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();
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;
}
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
Load entity node by nid
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
Get all languages enabled
Get alias for the path with translation
$alias = \Drupal::service('path_alias.manager')->getAliasByPath('node/5', 'en'); // Output: /welcome