Skip to content

Instantly share code, notes, and snippets.

@BBGuy
Last active May 3, 2024 14:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BBGuy/84175d84c66677f923da27256dd72ca7 to your computer and use it in GitHub Desktop.
Save BBGuy/84175d84c66677f923da27256dd72ca7 to your computer and use it in GitHub Desktop.
<?php
//******** user ***************//
$current_user = \Drupal::currentUser();
$current_user_id \Drupal::currentUser()->id();
$user = User::load($user_id);
//******** messenger - set messeges ***************//
// Messenger - (D7 drupal_set_message)
\Drupal::messenger()->addMessage(t('Show this message to the user.'));
// Message Types
\Drupal::messenger()->addMessage($message, 'status');
\Drupal::messenger()->addMessage($message, 'warning');
\Drupal::messenger()->addMessage($message, 'error');
// Another way of displaying error type messages.
\Drupal::messenger()->addError(t('The user account %id does not exist.', ['%id' => $uid]));
// Using t()
$text = t('My name is %name.<br>My age is %age.', ['%name' => $name, %age -> $age]);
// Formated Array messege
$formatted_array = print_r($array_data, TRUE);
$msg = t('Output array data: <pre>@data</pre>', ['@data' => $formatted_array]);
\Drupal::messenger()->addStatus(['#markup' => $msg]);
// HTML mutly line messege
$msg = t('<h2>Formatted message</h2><strong>Multi line output</strong><br>Line 1<br>Line 2');
\Drupal::messenger()->addStatus(['#markup' => $msg]);
// Add messenger to your class for use with $this->messenger
/**
* Gets the messenger.
*
* @return \Drupal\Core\Messenger\MessengerInterface
* The messenger.
*/
public function messenger() {
if (!isset($this->messenger)) {
$this->messenger = \Drupal::messenger();
}
return $this->messenger;
}
// **** working with nodes ******
// Check if an entity is a node.
if ($entity instanceof \Drupal\node\NodeInterface) {
$node = $entity;
}
// or
if ($entity->getEntityTypeId() == 'node') {
$node = $entity;
}
// check the bundle type of a node
$node_type = $entity->getType();
// Load by ID
use Drupal\node\Entity\Node; // Add to use section
$node = Node::load($nid);
//Load mathod 2 - https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet
$node_storage = \Drupal::entityTypeManager()->getStorage('node');
$node = $node_storage->load($nid);
// Get a node from a form
$node = $form_state->getFormObject()->getEntity();
$is_new = $node->isNew();
// Get node id.
$nid = $node->id();
// Get node title
$title = $product->getTitle(); // use this
$title = $product->title
// Get the published state.
$is_published = $node->isPublished();
// If we have a modaration workflow - we can get the state "Machine name".
$moderation_state = $node->moderation_state->value;
// Get a field value array
$node->get('field_name')->getValue();
$node->field_name->getValue();
// Get the 2nd value of a multi value field
$node->field_name->getValue()[1]['value'];
// Get the 3nd reference ID of a multi value entity reference field
$node->field_name->getValue()[2]['target_id'];
// Count the number of values
count($node->field_name->getValue())
// Get a single field value (shortest form)
$node->field_name->value;
// Single node entity reference field
$nid = $node->get('field_contact')->first()->getValue()['target_id'];
$node = Node::load($nid);
// or (shortest form)
$node->field_contact->target_id;
// Cycle a Entity reference fields
foreach ($node->field_po_lines as $reference) {
$entity_id = $reference->target_id;
$entity_storage = \Drupal::entityTypeManager()->getStorage('po_line');
$entity = $entity_storage->load($entity_id);
}
// Cycle a Entity reference fields (th long way)
foreach ($node->field_po_lines as $po_line) {
/** @var \Drupal\Core\Entity\Plugin\DataType\EntityReference $entityReference */
$entityReference = $po_line->get('entity');
/** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $entityAdapter */
$entityAdapter = $entityReference->getTarget();
/** @var \Drupal\Core\Entity\EntityInterface $referencedEntity */
$referencedEntity = $entityAdapter->getValue();
}
// Get all the referenced entities in one go
$all__referenced_entities = $node->get('field_po_lines')->referencedEntities();
// Create node - need to include:
use Drupal\node\Entity\Node;
// Create a node mathod 1a - simple
$node = Node::create(['type' => 'article', 'title' => 'Sample article API', 'path' => ['alias' => '/sample-article-api']]);
$node->save();
// Create a node mathod 1b - more details
$data = [
'uid' => $user->id(),
'name' => 'admin',
'type' => 'article',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'title' => $this->randomMachineName(),
'body' => 'body text',
'multivalue_field' => [ ['value' => 'first'], ['value' => 'second'] ]
'status' => 1,
'created' => '1435019805',
];
$node = Node::create($data);
$node->save();
// Create a node mathod 2 - field by field
$node = Node::create(['type' => 'article']);
$node->set('title', 'Title');
$node->set('field_text', 'My text');
$node->save();
// Create a node mathod 3 - field by field
\Drupal::entityTypeManager()->getStorage('node')->create(['type' => 'article', 'title' => 'Node title']);
// Seting Fields
// Title filed
$node->set('title', 'Title');
// Text field
$node->set('field_text', 'My text');
// Created date in a unix time stamp
$node->set('created', time());
// Date fields are text
$node->set('field_date', date('Y-m-d', time()));
$node->set('field_datetime', date('Y-m-d\TH:i:s', time()));
// User
$po_node->set('field_user', \Drupal::currentUser()->id());
// reference field (two options)
$node->field_user->target_id = $user_id;
$node->field_user->entity = $user;
// Multiple values
$node->field_user[] = ['target_id' => $user_id];
$node->save();
// Populate a multivalue field for a string holding comma delimited values
$value = '1,2,3,4';
$value_array = explode(',', $value);
foreach ($value as $key => $value) {
$value_array[$key] = ['value' => trim($value)];
}
$node->set('multivalue_field', $value_array;
// Create custom entities
/* @var \Drupal\custom_module\Entity\CustomEntity $newentity */
$newentity = CustomEntity::create();
// ***** Multilingual **** //
// Load a node in the current language.
$current_lang_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
$node = Node::load($id);
if ($node->hasTranslation($current_lang_code)) {
$node = $node->getTranslation($current_lang_code);
}
// **** working with ULs ****** //
// Get the curent path (will give you the internal path i.e. node/5)
$internalt_path = \Drupal::service('path.current')->getPath();
// Get the curent path alias will give you the path alias i.e. /the_path/to/a_page)
$current_path = \Drupal\Core\Url::fromRoute('<current>')->toString();
// Get the path alias from the internal path
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($internalt_path);
// Get the path alias of node/5
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath('node/5');
// Get a localised URL for node/5
$current_lang_code = \Drupal::languageManager()->getCurrentLanguage()->getId();
// The alias does not contain the language prefex so we need to add it.
$node_url = "/$current_lang_code" . \Drupal::service('path_alias.manager')->getAliasByPath('/node/5', $current_lang_code);
// Get the path arguments into an array /arg1/arg2/...
$path_args = explode('/', $current_path);
$arg1 = $path_args[1]; // $path_args[0] - is empty resulting from the leading slash and should be ignored
$arg2 = $path_args[2];
// Get the query strings: {url}/arg1/arg?p1=123&p2=456
$p1 = \Drupal::request()->query->get('p1');
$p2 = \Drupal::request()->query->get('p2');
// Getting the referer from the request.
$request = \Drupal::request();
$referer = $request->headers->get('referer');
// Converting the referer into a request and getting its query strings
use Symfony\Component\HttpFoundation\Request;
.....
$ref_request = Request::create($referer, 'GET');
$staff_id = $ref_request->query->get('qs1');
$return_url = $ref_request->query->get('qs2');
// Redirect from a form submit
public function submitForm(array &$form, FormStateInterface $form_state) {
// uses use Drupal\Core\Url;
....
$url = Url::fromUserInput('/arg1/arg2/do-it', ['query' => ['qry-string' => $nid]]);
$form_state->setRedirectUrl($url);
}
// Redirect from inside a hook (preserving a query string)
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;
....
$redirect_url .= '/new_url?' . \Drupal\Component\Utility\UrlHelper::buildQuery(['qs1' => $staff_id]);
$redirect = new RedirectResponse($redirect_url);
$redirect->send();
// Get a URL for a drupal route (views example)
$url = Url::fromRoute('view.view_name.page_1');
// Add options (adding a class in this example)
$link_options = [
'attributes' => [
'class' => [
'btn',
],
],
];
$url->setOptions($link_options);
// get the link
$link = new Link(t('Show All'), $url);
// Use drupal consol to list all the rout names
$ drupal router:debug
// Redirect from a Controller (derived from ControllerBase)
// Add to the uses section: use Drupal\Core\Url;
$destination = Url::fromUserInput('/go-somplace-else');
return $this->redirect($destination->getRouteName());
// Using Symfony
use Symfony\Component\HttpFoundation\RedirectResponse;
return new RedirectResponse(Url::fromUserInput('/some-url')->toString());
return new RedirectResponse(Url::fromRoute('<front>')->toString());
//******** State API ***************//
// States - Get a state with a defult of FALSE
\Drupal::state()->get('my_state_var_name', FALSE)
//******** Cache API ***************//
// Cache API data for 24 hours:
$cid = 'test_module_api_product_data';
if ($cache = \Drupal::cache()->get($cid)) {
$products = $cache->data;
}
else {
$products = $this->Api->getProducts();
// Cache for 24 hours.
$expire = time() + 24*60*60;
\Drupal::cache()->set($cid, $products, $expire);
}
// Using bins
$cache = \Drupal::cache()->get($cid)
// is the same as calling:
$cache = \Drupal::cache('default')->get($cid)
// and will get the data from the cache_default table.
// you can use other bins:
$cache = \Drupal::cache('data')->get($cid)
$cache = \Drupal::cache('entity')->get($cid)
$cache = \Drupal::cache('dynamic_page_cache')->get($cid)
//for custom bins see:
https://www.hashbangcode.com/article/drupal-8-custom-cache-bins
//******** Configuration API ***************//
// read a value.
$config = \Drupal::config('mymodule.myconfig');
$config_var = $config->get('var_name');
// One liner.
$config_var = \Drupal::config('mymodule.myconfig')->get('var_name');
// Read a value from a config form and save.
$field_value = (int) $form_state->getValue('my_state_field_name');
\Drupal::config('mymodule.myconfig')
->set('var_name', $field_value)
->save();
//******** Watchdog ***************//
// Logger/watchdog
$logger = \Drupal::logger('channel name'); // $channel - The name of the channel Can be any string, but the general practice is to use the name of the subsystem/module calling this.
$logger->info('log a simple info message');
$logger->notice('log a simple notice message');
$logger->warning('log a simple warning message');
$logger->error('log a simple error message');
// Argument examples
$logger->info('Starting execution of @module_cron() job %job_text, execution of @module_previous_cron() took @time.', [
'@module' => $module,
'%job_text' => 'some text',
'@module_previous' => $module_previous,
'@time' => Timer::read('cron_' . $module_previous) . 'ms',
]);
// Multi lines example:
$this->logger->info("Import completed in @time seconds.<br>
Imported: @imported.<br>
Updated: @updated<br>
Deleted: @deleted",
[
'@time' => $group_run_time,
'@imported' => $import_count,
'@updated' => $updated,
'@deleted' => $deleted,
]);
// @todo - Not sure about this notation.
$this->logger->info('Received a payload from client {clientId}', ['clientId' => $clientId]);
// complex use
$context = [
'channel' => $type,
];
$error_args = [
'@api_path' => $api_path,
'@response_code' => $api_response_code,
'@response_error' => $api_response_error,
'@response_data' => print_r($api_response, TRUE)
];
$error_msg = t('Get request failed for @api_path, code: @response_code error: @response_error,
<pre><code> Response data: @response_data</code></pre>', $error_args);
}
$logger->error($message, $context);
// Get the list of options for a list field.
$e_manager=\Drupal::entityManager();
$field_definition = $e_manager->getFieldDefinitions("node","person")["field_profession"];
$profession_allowed_values = $field_definition->getFieldStorageDefinition()->toArray()["settings"]["allowed_values"];
// Can be used to get the display of the field value
$profession_id = $node->field_judge_panel->value
$profession_name = $profession_allowed_values[$profession_id];
<?php
// Catch all
try {
// Some code
return TRUE;
}
catch (\Exception $e) {
$this->logger->error("Code failed with exception: @exception", [
'@sku' => $part_number,
'@exception' => $e->getMessage()
]);
return FALSE;
}
catch (\Throwable $e) {
$this->logger->error("Code failed with Throwable exception: @exception", [
'@sku' => $part_number,
'@exception' => $e->getMessage()
]);
return FALSE;
}
// Detailed logg of the exception
try {
// ....
}
catch (\Exception $e) {
$logger = \Drupal::logger('my_module_name');
$logger>error(t('function_name Exception:') . $e->getMessage(), array('exception' => $e));
return [];
}
<?php
//** Patarn 1: Add multiple submits to a config from. **//
public function buildForm(array $form, FormStateInterface $form_state): array {
// Array elements
$form['some_element'] = [
'#type' => 'some_type',
...
];
// New Submit
$form['test_submit'] = [
'#type' => 'submit',
'#name' => 'run-test',
'#value' => $this->t('Run test'),
'#submit' => [ [$this, 'runTest'] ]
];
}
// This will be called if ragulr submit is pressed.
public function submitForm(array &$form, FormStateInterface $form_state): void {
\Drupal::messenger()->addMessage('Normal Form Submit', 'status');
// ... some code.
parent::submitForm($form, $form_state);
}
// This will be called if the "Run test" submit is pressed.
public function runTest(array &$form, FormStateInterface $form_state) {
\Drupal::messenger()->addMessage('Run Test', 'status');
}
//** Patarn 2: Add optional submits to a config from. **//
public function buildForm(array $form, FormStateInterface $form_state): array {
// Array elements
$form['some_element'] = [
'#type' => 'some_type',
...
];
// New Submit
$form['test_submit'] = [
'#type' => 'submit',
'#value' => $this->t('Run Test'),
'#id' => 'run-test',
];
}
public function submitForm(array &$form, FormStateInterface $form_state): void {
\Drupal::messenger()->addMessage('Normal Form Submit', 'status');
// ... some code.
// Optional actions
$action = $form_state->getTriggeringElement();
$action_id = $action['#id'];
if ($action_id == 'run-test') {
\Drupal::messenger()->addMessage('Run Test', 'status');
}
parent::submitForm($form, $form_state);
}
<?php
use Drupal\Core\Link;
use Drupal\Core\Url;
// Get the Url object for a node edit form
$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
// Get an internal URL.
$url = Url::fromUri( 'internal:/someplace/on_the_site');
// Convert to link
$link = new Link('Click me', $url);
$link_txt = $link->toString();
// URL from URI
$url = \Drupal::service('file_url_generator')->generateString($uri); // reletive
$url = \Drupal::service('file_url_generator')->generateAbsoluteString($uri); // FULL
<?php
// Set variables for a node template
/*
* Implements theme_preprocess_node
*
*/
function my_module_preprocess_node(&$variables) {
$node = &$variables['node'];
$view_mode = &$variables['view_mode'];
$bundle = $node->bundle();
switch ($bundle) {
case 'home_page':
$variables['page'] = 'home';
break;
case 'landing_page':
$variables['page'] = 'landing';
$variables['display_submitted'] = False;
break;
case 'report_page':
$variables['page'] = 'report';
$one = $node->field_one->value;
$variables['one'] = $one;
break;
}
}
in something.template.html.twig
<div>This is a {{ page }} page</div>
<?php
// hook_node_presave() example
// Set the node title to first and last name.
// You should disable the title in the manage form display.
function my_module_node_presave($node){
$first_name = $node->field_first_name->value;
$last_name = $node->field_last_name->value;
$name = $first_name;
if (!empty($last_name)) {
$name .= ' ' . $last_name;
}
$node->set('title', $name);
}
<?php
// User get and load functions.
$current_user = \Drupal::currentUser();
$current_user_id \Drupal::currentUser()->id();
$user = User::load($user_id);
// Check if a user is logged in / Authenticated.
\Drupal::currentUser()->isAuthenticated()
// Check if a user has a role.
$current_user = \Drupal::currentUser();
$user_roles = $current_user->getRoles();
if (in_array('administrator', $user_roles)) {
// Do stuff
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment