Last active
January 11, 2022 19:36
-
-
Save druman/1678b628b068dc84b7f7da8f279de1cb to your computer and use it in GitHub Desktop.
Drupal 8 tweaks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// thx drupal8.ovh | |
//// 1) How to get the current language in Drupal 8 | |
//To get the lanuage code: | |
$language = \Drupal::languageManager()->getCurrentLanguage()->getId(); | |
//To get the language name: | |
$language = \Drupal::languageManager()->getCurrentLanguage()->getName(); | |
//// 2) Create a node programmatically (node type: article) | |
$language = \Drupal::languageManager()->getCurrentLanguage()->getId(); | |
$node = \Drupal\node\Entity\Node::create(array( | |
'type' => 'article', | |
'title' => 'The title', | |
'langcode' => $language, | |
'uid' => 1, | |
'status' => 1, | |
'body' => array('The body text'), | |
'field_date' => array("2000-01-30"), | |
//'field_fields' => array('Custom values'), // Add your custon field values like this | |
)); | |
$node->save(); | |
//// 3) Create a user account programmatically | |
$language = \Drupal::languageManager()->getCurrentLanguage()->getId(); | |
$user = \Drupal\user\Entity\User::create(); | |
//Mandatory settings | |
$user->setPassword('password'); | |
$user->enforceIsNew(); | |
$user->setEmail('email'); | |
$user->setUsername('user_name');//This username must be unique and accept only a-Z,0-9, - _ @ . | |
//Optional settings | |
$user->set("init", 'email'); | |
$user->set("langcode", $language); | |
$user->set("preferred_langcode", $language); | |
$user->set("preferred_admin_langcode", $language); | |
//$user->set("setting_name", 'setting_value'); | |
$user->activate(); | |
//Save user | |
$res = $user->save(); | |
//// 4) Get taxonomy vocabulary list | |
$vocabularies = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple(); | |
//// 5) Get taxonomy terms of a vocabulary | |
//Using entityQuery, you can get the taxonomy terms of a particular vocabulary. | |
$query = \Drupal::entityQuery('taxonomy_term'); | |
$query->condition('vid', "tags"); | |
$query->sort('weight'); | |
$tids = $query->execute(); | |
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids); | |
//If you want to get several vocabulary, use OR condition like that. | |
$query_or->condition('vid', "tags"); | |
$query_or->condition('vid', "test"); | |
$query->condition($query_or); | |
//Get Taxonomy name | |
$name = $term->toLink()->getText(); | |
//Create link to the term | |
$link = \Drupal::l($term->toLink()->getText(), $term->toUrl()); | |
// !!! Get name & tid from loaded terms | |
foreach ($terms as $term) { | |
$name = $term->get('name')->getString(); | |
$tid = $term->get('tid')->getString(); | |
} | |
//// 6) Add CSS stylesheets to a module | |
/* | |
1. Styling a programmatically created block. | |
1.1 Add a librarie. | |
-> Create a file modulename.libraries.yml | |
-> Add css file, Example: */ | |
my-block-styling: | |
version: 1.x | |
css: | |
theme: | |
css/style.css: {} | |
/* | |
1.2 Create CSS file and put it in to the module_folder/css/style.css | |
1.3 Attach librarie to the block | |
In your build() methode, add to the output array, | |
*/ | |
$output[]['#attached']['library'][] = 'modulename/my-block-styling'; | |
// Add / Attaching a library from a Twig template | |
{{ attach_library('MODULENALE/my-style') }} | |
/* To remove a style sheet | |
stylesheets-remove: */ | |
- '@classy/css/components/tabs.css' | |
- core/assets/vendor/normalize-css/normalize.css | |
//// 7) Get the current page URI | |
$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 provide several way to do the same things, You can also use following syntax. | |
$path = \Drupal::request()->attributes->get('_system_path'); | |
$current_uri = \Drupal::request()->getRequestUri(); | |
$current_path = \Drupal::service('path.current')->getPath(); | |
$result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path); | |
// Get the url of the request | |
// This return the url displayed on the browser. | |
$page = \Drupal::request()->getRequestUri(); | |
//// 8) Create a link with Drupal 8 like l() and url() on D7 | |
$link = \Drupal\Core\Link::fromTextAndUrl($text, $url); | |
//// № 9) Return JSON array as resut | |
//Example 1. | |
return new \Symfony\Component\HttpFoundation\JsonResponse($array); | |
//Example 2. | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
public function get_result() { | |
$output = array(); | |
$output[] = array('time' => date("Y-m-d H:i:s")); | |
$output[] = array('result'=> "OK"); | |
return new JsonResponse($output); | |
} | |
//// № 10) Create taxonomy term programmatically | |
$term = \Drupal\taxonomy\Entity\Term::create([ | |
'vid' => 'test_vocabulary', | |
'name' => 'My tag', | |
]); | |
$term->save(); | |
// With options | |
$term = \Drupal\taxonomy\Entity\Term::create([ | |
'vid' => 'test_vocabulary', | |
'langcode' => 'en', | |
'name' => 'My tag', | |
'description' => [ | |
'value' => '<p>My description.</p>', | |
'format' => 'full_html', | |
], | |
'weight' => -1, | |
'parent' => array(0), | |
]); | |
$term->save(); | |
//Add term with a custom field. Example : 'field_url' | |
$term = Term::create([ | |
'vid' => 'test_vocabulary', | |
'name' => 'The Name', | |
'field_url' => [$url], | |
]); | |
$term->save(); | |
//Check Taxonomy name exist | |
$query = \Drupal::entityQuery('taxonomy_term'); | |
$query->condition('vid', "test_vocabulary"); | |
$query->condition('name', "My tag"); | |
$tids = $query->execute(); | |
//// № 11) Get the current user | |
//use Drupal\user\Entity\User; | |
$userCurrent = \Drupal::currentUser(); | |
$user = \Drupal\user\Entity\User::load($userCurrent->id()); | |
$name = $user->getUsername(); | |
// How To check if the current page is the homepage | |
$is_front_page = \Drupal::service('path.matcher')->isFrontPage(); | |
//// № 12) Get node id (NID) from url | |
$node = \Drupal::routeMatch()->getParameter('node'); | |
if ($node) { | |
$nid = $node->id(); | |
} | |
//// № 13) Get field value of a Node / Entity | |
//1 : Example: | |
$value = $node->get($field)->value; | |
$target = $node->get($field)->target_id; // For entity ref | |
//2 Example: | |
$field = 'field_thefieldname'; | |
$index = 0; | |
$a = $node->toArray(); | |
if (isset($a[$field][$index]['value'])) { | |
$value = $a[$field][$index]['value']; | |
} | |
//3 : Get / Render image (Show current user's picture) | |
$userCurrent = \Drupal::currentUser(); | |
$user = \Drupal\user\Entity\User::load($userCurrent->id()); | |
$renderd_image = $user->get('user_picture')->first()->view(); | |
Or for multiple values | |
foreach ($node->get('field_images')->getValue() as $key => $image) { | |
$image = $node->field_images[$key]->view($settings); | |
} | |
//Example Of $settings | |
$settings = ['settings' => ['image_style' => 'thumbnail']]; | |
//// № 14) Add a message to Drupal 8 Log system (/admin/reports/dblog) | |
\Drupal::logger("mymodule")->alert("Message"); | |
\Drupal::logger("mymodule")->critical("Message"); | |
\Drupal::logger("mymodule")->debug("Message"); | |
\Drupal::logger("mymodule")->emergency("Message"); | |
\Drupal::logger("mymodule")->error("Message"); | |
\Drupal::logger("mymodule")->info("Message"); | |
\Drupal::logger("mymodule")->notice("Message"); | |
\Drupal::logger("mymodule")->warning("Message"); | |
//// № 15) Update a node / Entity programmatically | |
//Example 1 : Update title | |
$node = \Drupal\node\Entity\Node::load($nid); | |
$node->setTitle('The new Title') | |
$node->save(); | |
//Example 2 : Update a field ('body' and 'field_name') | |
$node = \Drupal\node\Entity\Node::load($nid); | |
$node->set("body", 'New body text'); | |
$node->set("field_name", 'New value'); | |
$node->save(); | |
function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) { | |
if ($entity->getEntityType()->id() == 'node') { | |
$entity->setTitle('The new Title'); | |
//CAUTION : Do not save here, because it's automatic. | |
} | |
} | |
//// № 16) Create a custom permission in custom module (mymodule) | |
/* Step 1. | |
Create if not exist yet, mymodule.permissions.yml (root of mymodule) | |
Add your new permission like: */ | |
mymodule test_permission: | |
title: 'My Test Permission' | |
description: 'The description' | |
restrict access: false | |
/* Step 2. | |
On your mymodule.routing.yml */ | |
mymodule.home: | |
path: 'test/home' | |
defaults: | |
_controller: '\Drupal\mymodule\Controller\Test::home' | |
_title: 'My test Home' | |
requirements: | |
_permission: 'mymodule test_permission' | |
//Set permissions on : /admin/people/permissions | |
//// № 17) Get args from URL | |
$current_url = Url::fromRoute('<current>'); | |
$path = $current_url->toString(); | |
//OR of you want to get the url without language prefix | |
$path = $current_url->getInternalPath(); | |
$path_args = explode('/', $path); | |
//Method 2: (Get first argument from url on Drupal 8) | |
$request = \Drupal::request(); | |
$current_path = $request->getPathInfo(); | |
$path_args = explode('/', $current_path); | |
$first_argument = $path_args[1]; | |
//// № 18) Page Redirect | |
return new \Symfony\Component\HttpFoundation\RedirectResponse('/node/17/edit'); | |
return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('<front>')); | |
return new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url('user.page')); | |
//Form redirection on submit | |
//Redirect to the user page ( Redirection on form submit) | |
$form_state->setRedirect('user.page'); | |
//Redirect to a custom page | |
$form_state->setRedirect('your.module.route.name'); | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
$form_state->setRedirect('your.module.route.name'); | |
} | |
//// № 19) Add custom class to the elements of a Views | |
/** | |
* Add classes to a view | |
* @param $vars | |
*/ | |
function MYTHEME_preprocess_views_view_list(&$vars) { | |
if ($vars['view']->name == 'article') { | |
$view = $vars['view']; | |
foreach ($view->result as $row_index => $result) { | |
$val1 = strlen($result->field_body[0]['rendered']['#markup']); | |
$val2 = strlen($result->field_body[0]['raw']['safe_value']); | |
$vars['classes_array'][$row_index] .= ' my-class'; | |
} | |
} | |
} | |
//// № 20) Add twig template to a custom Module, Block or Page | |
https://www.drupal8.ovh/en/tutoriels/140/add-twig-template-to-a-custom-module-block-or-page | |
//// № 21) Call URL on Drupal 8, Like drupal_http_request() on D7 | |
use GuzzleHttp\Exception\RequestException; | |
$url = "http://www.domail.com"; | |
$client = \Drupal::httpClient(); | |
try { | |
$response = $client->get($url); | |
$data = $response->getBody(); | |
$code = $response->getStatusCode(); | |
$header = $response->getHeaders(); | |
} | |
catch (RequestException $e) { | |
watchdog_exception('my_module', $e); | |
} | |
//https://www.drupal.org/node/1862446 | |
//// № 22) JSON Encode and Decode | |
use Drupal\Component\Serialization\Json; | |
$json = Json::encode($data); | |
$data = Json::decode($json); | |
//// № 23) Change Drupal 8 text field maximum length | |
https://www.drupal8.ovh/en/tutoriels/223/change-drupal-8-text-field-maximum-length | |
//// № 24) Alter a view. Edit view result programmatically | |
function MYMODULE_views_pre_render(&$view) { | |
if ($view->name == 'view_myviewname') { | |
$result = $view->result; | |
foreach ($result as $i => $row) { | |
$view->result[$i]->field_field_myfieldtext[0]['rendered']['#markup'] = "The new text"; | |
} | |
} | |
} | |
//// № 25) How to create a JSON web service | |
/* Create a module. | |
Here : mywebservice | |
Create route, the Web Service path. | |
Example: */ | |
mywebservice.multiply: | |
path: '/mywebservice/maths/multiply' | |
defaults: | |
_controller: '\Drupal\mywebservice\Controller\MyWebService::multiply' | |
_title: 'MyWebService' | |
requirements: | |
_permission: 'access content' | |
/* Create webservice Controller | |
Example: */ | |
// UNCOMMENT!!! <?php | |
// | |
namespace Drupal\mywebservice\Controller; | |
// | |
use Drupal\Core\Controller\ControllerBase; | |
use Symfony\Component\HttpFoundation\JsonResponse; | |
/** | |
* Class MyWebService. | |
*/ | |
class MyWebService extends ControllerBase { | |
/** | |
* Multiply. | |
*/ | |
public function multiply() { | |
$request = \Drupal::request(); | |
$output['a'] = $request->get('a'); | |
$output['b'] = $request->get('b'); | |
$output['result'] = $output['a'] * $output['b']; | |
return new JsonResponse($output); | |
} | |
} | |
/* | |
Test the web service | |
Visit : http://yourdomain.loc/mywebservice/maths/multiply | |
Must return a JSON : {"a":null,"b":null,"result":0} | |
Visit : http://yourdomain.loc/mywebservice/maths/multiply?a=5&b=2 | |
Must return a JSON : {"a":"5","b":"2","result":10} | |
*/ | |
//// № 26) Change a metatag dynamicly | |
//Example: Add <meta http-equiv="refresh" content="30"> | |
$data = [ | |
'#tag' => 'meta', | |
'#attributes' => [ | |
'http-equiv' => 'refresh', | |
'content' => '30', | |
], | |
]; | |
$output['#attached']['html_head'][] = [$data, 'refresh']; | |
//// № 27) How more than 100 terms in taxonomy administration (overview) page | |
//Example : Show 1000 items on admin page. | |
//Check settings: | |
drush cget taxonomy.settings | |
//Set number to 1000: | |
drush cset taxonomy.settings terms_per_page_admin 1000 | |
?> |
$vid = "1";
$name = "cars";
$vocabularies = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple();
if (!isset($vocabularies[$vid])) {
$vocabulary = \Drupal\taxonomy\Entity\Vocabulary::create(array(
'vid' => $vid,
//'machine_name' => $vid,
'description' => '',
'name' => $name,
));
$vocabulary->save();
}
else {
// Vocabulary Already exist
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vid);
$tids = $query->execute();
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome! Thanks. One thing I was wondering if you knew. How to create a vocabulary if it doesn't already exist. Might be worth adding.