{"id":21409556,"url":"https://github.com/mahmoudsayed96/drupal-code-snippets","last_synced_at":"2025-07-14T01:31:04.068Z","repository":{"id":124431281,"uuid":"404883801","full_name":"MahmoudSayed96/drupal-code-snippets","owner":"MahmoudSayed96","description":"Drupal CMS development tips","archived":false,"fork":false,"pushed_at":"2025-02-02T08:12:18.000Z","size":730,"stargazers_count":5,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-07T21:45:04.160Z","etag":null,"topics":["drupal","php","symfony","tips"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MahmoudSayed96.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-09-09T22:13:25.000Z","updated_at":"2025-02-02T12:27:10.000Z","dependencies_parsed_at":null,"dependency_job_id":"6f3e16ca-ae40-4457-afaf-7709ef936022","html_url":"https://github.com/MahmoudSayed96/drupal-code-snippets","commit_stats":null,"previous_names":["mahmoudsayed96/drupal-code-snippets"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MahmoudSayed96/drupal-code-snippets","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahmoudSayed96%2Fdrupal-code-snippets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahmoudSayed96%2Fdrupal-code-snippets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahmoudSayed96%2Fdrupal-code-snippets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahmoudSayed96%2Fdrupal-code-snippets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MahmoudSayed96","download_url":"https://codeload.github.com/MahmoudSayed96/drupal-code-snippets/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MahmoudSayed96%2Fdrupal-code-snippets/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":265230755,"owners_count":23731437,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["drupal","php","symfony","tips"],"created_at":"2024-11-22T17:27:05.987Z","updated_at":"2025-07-14T01:31:04.055Z","avatar_url":"https://github.com/MahmoudSayed96.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"## Drupal PHP cheatsheet\n\n- [Custom Module Development](#custom-module-development)\n  - [URL](#url)\n  - [Images](#images)\n  - [JavaScript](#javascript)\n  - [DateTime](#datetime)\n  - [User](#user)\n  - [Node](#node)\n  - [Form](#form)\n  - [Taxonomy](#taxonomy)\n  - [Block](#block)\n  - [Views](#views)\n  - [Database](#database)\n    - [DATABASE OPERATIONS](#database-operations)\n    - [Select](#select)\n    - [Update](#update)\n    - [Delete](#delete)\n    - [Insert](#insert)\n  - [Services](#services)\n  - [Theme](#theme)\n  - [Drush](#drush)\n  - [Links](#links)\n  - [Twig](#twig)\n  - [Paragraphs](#paragraphs)\n  - [General](#general)\n  - [DRUPAL CONSOLE](#drupal-console)\n\n# Custom Module Development\n\n- Module file structure\n\n```\n|-- modules\n  | -- custom\n    |-- hello_world\n      |-- hello_world.info.yml\n      |-- hello_world.routing.yml\n      |-- src\n        |-- Controller\n```\n\n- .info.yml:\n  \u003e Contains all information about module [name, description, core, version, type]\n\n```yml\nname: Hello World Module\ndescription: Creates a page showing \"Hello World\".\npackage: Custom\n\ntype: module\ncore: 8.x\ncore_version_requirement: ^8 || ^9\n```\n\n- .routing.yml\n  \u003e Containes custom routing refear to controller callback function\n\n```yml\nhello_world.my_page:\n  path: \"/mypage/page\"\n  defaults:\n    _controller: '\\Drupal\\hello_world\\Controller\\HelloWorldController::myPage'\n    _title: \"My first page in Drupal\"\n  requirements:\n    _permission: \"access content\"\n```\n\n\u003cstrong\u003ehello_world.my_page\u003c/strong\u003e\u003cbr\u003e\n\n\u003cp\u003e\n  This is the machine name of the route. By convention, route machine names should be module_name.sub_name. When other parts of the code need to refer to the route, they will use the machine name.\n\u003c/p\u003e\n\u003cstrong\u003epath\u003c/strong\u003e\u003cbr\u003e\n\u003cp\u003eThis gives the path to the page on your site. Note the leading slash (/).\u003c/p\u003e\n\u003cstrong\u003edefaults\u003c/strong\u003e\u003cbr\u003e\n\u003cp\u003eThis describes the page and title callbacks. @todo: Where can these defaults be overridden?\u003c/p\u003e\n\u003cstrong\u003erequirements\u003c/strong\u003e\u003cbr\u003e\n\u003cp\u003eThis specifies the conditions under which the page will be displayed. You can specify permissions, modules that must be enabled, and other conditions.\u003c/p\u003e\n\n---\n\n## URL\n\n### URL generation###\n\n@see \u003chttps://www.hashbangcode.com/article/drupal-9-programmatically-creating-and-using-urls-and-links\u003e. \u003cbr\u003e\n@see \u003chttps://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/class/Url/8.2.x\u003e.\n\n\u003e When adding a URL into a string, for instance in a text description, core recommends we use the `\\Drupal\\Core\\Url` class.\n\u003e This has a few handy methods:\n\n- Internal URL based on a route - ### `Url::fromRoute()`### , Example: `Url::fromRoute('user.register')-\u003etoString()`\n- Internal URL based on a path - ### `Url::fromInternalUri()`### , Example: `Url::fromInternalUri('node/add')`\n- External URL - ### `Url::fromUri`### , Example: `Url::fromUri('https://www.acquia.com')`\n  \u003e When you need to constrict and display the link as text you can use the `toString()` method: `Url::fromRoute('user.register')-\u003etoString()`.\n\nShort snippet that shows how to get url parameters in drupal 8.\nto get query parameter form the url, you can us the following.\nIf you have the url for example `/page?uid=123\u0026num=452`.\nTo get all params, use:.\n`$param = \\Drupal::request()-\u003equery-\u003eall();`.\nTo get \"uid\" from the url, use:.\n`$uid = \\Drupal::request()-\u003equery-\u003eget('uid');`.\n\nTo get \"num\" from the url, use:\n\n`$num = \\Drupal::request()-\u003equery-\u003eget('num');`\n\n// Remove ar or en from the path.\n```php $path = preg_replace('/\\/(ar|en)/', '', $request-\u003egetPathInfo()); ```\n    \n### URL in TWIG ###\n```twig\n{# Link to frontpage view. #}\n\u003ca href=\"{{ path('view.frontpage.page_1') }}\"\u003e{{ 'View all content'|t }}\u003c/a\u003e\n\u003cbr\u003e\n{# Link to user entity/profile page. #}\n\u003ca href=\"{{ path('entity.user.canonical', {'user': user.id}) }}\"\u003e{{ 'View user profile'|t }}\u003c/a\u003e\n\u003cbr\u003e\n{# Link to node page. #}\n\u003ca href=\"{{ path('entity.node.canonical', {'node': node.id}) }}\"\u003e{{ 'View node page'|t }}\u003c/a\u003e\n\u003cbr\u003e\n{# Add a destination query parameter. Simple Example #}\n\u003ca href=\"{{ path('user.login', {}, {'query': {'destination': path('\u003ccurrent\u003e') }}) }}\"\u003e{{ 'View node page'|t }}\u003c/a\u003e.\n\u003cbr\u003e\n{# Add a destination query parameter. Advanced Example, registration_form.simple_form is a custom route from a custom module with the name registration_form #}\n{% set redirect_path = path('registration_form.simple_form', {'node': node.id}) %}\n\u003ca href=\"{{ path('user.register',{},{'query':{'destination': redirect_path }}) }}\"\u003e{{ 'Register'|t }}\u003c/a\u003e\n```\n\n## Images\n\n### Render images with image styles\n\n@source https://www.webomelette.com/how-render-your-images-image-styles-drupal-8\n\n#### URL only\n\n```php\n$style = \\Drupal::entityTypeManager()-\u003egetStorage('image_style')-\u003eload('thumbnail');\n$url = $style-\u003ebuildUrl('public://my-image.png');\n```\n\n#### Render image\n\n```php\n$render = [\n  '#theme' =\u003e 'image_style',\n  '#style_name' =\u003e 'thumbnail',\n  '#uri' =\u003e 'public://my-image.png',\n  // optional parameters\n];\n```\n\n#### Example\n\n@todo to be refined.\n\n```php\nif ($paragraph \u0026\u0026 $paragraph-\u003ehasField('field_image') \u0026\u0026 !$paragraph-\u003eget('field_image')-\u003eisEmpty()) {\n  $entity_img_id = $paragraph-\u003eget('field_image')-\u003efirst()-\u003egetValue()['target_id'];\n  $image = \\Drupal::entityTypeManager()-\u003egetStorage('file')-\u003eload($entity_img_id);\n  $style = \\Drupal::entityTypeManager()-\u003egetStorage('image_style')-\u003eload('thumbnail');\n  $uri = $style-\u003ebuildUrl($image-\u003egetFileUri());\n\n  return [\n    '#theme' =\u003e 'image',\n    '#style_name' =\u003e 'thumbnail',\n    '#uri' =\u003e $uri,\n  ];\n}\n```\n\n#### Responsive image\n\n```php\n$file = $paragraph-\u003eget('field_image')-\u003eentity;\n\nif ($file) {\n  $image = \\Drupal::service('image.factory')-\u003eget($file-\u003egetFileUri());\n\n  $logo_build = [\n    '#theme' =\u003e 'responsive_image',\n    '#responsive_image_style_id' =\u003e 'promoted_teaser',\n    '#uri' =\u003e $file-\u003egetFileUri(),\n  ];\n\n  // Add the file entity to the cache dependencies.\n  // This will clear our cache when this entity updates.\n  $renderer = \\Drupal::service('renderer');\n  $renderer-\u003eaddCacheableDependency($logo_build, $file);\n\n  $build['#image_p'.$paragraph_counter] = $logo_build;\n}\n```\n\n### Load media entity \u0026 get a field\n\n```\nuse Drupal\\media\\Entity\\Media;\n\n$media = Media::load($nid);\n$file_uri = $media-\u003efield_media_file-\u003eentity-\u003egetFileUri();\n```\n\n### Show Image Field In Twig\n\n- Get the image as tag `\u003cimg\u003e`\n\n```twig\n{{fields.field_my_image_field.content|render|striptags('\u003cimg\u003e')|trim|raw}}\n```\n\n- Get the image as URL\n\n```twig\n{{fields.field_my_image_field.content|render|striptags|trim|raw}}\n```\n\n### show you how to loop images in Twig and dynamically add image styles to them in Drupal 8.\n\n```twig\n{% for item in content.field_images['#items'] %}\n  {% set image = {\n    '#theme':      'image_style',\n    '#style_name': 'medium',\n    '#uri':        item.entity.uri.value,\n    '#alt':        item.alt,\n    '#width':      item.width,\n    '#height':     item.height\n  } %}\n  {{ image }}\n{% endfor %}\n```\n\n## JavaScript\n\n### Drupal 8 Js, how to create a global Drupal Js function\n\n```javascript\n/**\n * Attaches the single_datetime behavior.\n *\n * @type {Drupal~behavior}\n */\n(\n  function ($, Drupal, drupalSettings) {\n    \"use strict\";\n    Drupal.behaviors.leafletCurrentLocation = {\n      attach: function (context, drupalSettings) {\n        // Code....\n      },\n    };\n  }\n)(jQuery, Drupal, drupalSettings);\n```\n\n### JavaScript behaviors\n\n```javascript\n(function ($, Drupal, drupalSettings, once) {\n  Drupal.behaviors.mainBehavior = {\n    attach: function (context, drupalSettings) {\n      once(\"mainBehavior\", \"html\", context).forEach(function () {\n        console.log(drupalSettings);\n        console.log(context);\n      });\n    },\n  };\n})(jQuery, Drupal, drupalSettings, once);\n```\n\n### How to Run a JavaScript Code at Browser Closing Time\n\n```javascript\n(function ($) {\n  Drupal.behaviors.page_load_progress = {\n    attach: function (context, settings) {\n      window.onbeforeunload = close_event_function;\n      function close_event_function() {\n        //Enter your code before run window close;\n        return null;\n      }\n    },\n  };\n})(jQuery);\n```\n\n## DateTime\n\n### Inserting the value from Datetime field form\n@see https://drupal.stackexchange.com/questions/204103/inserting-the-value-from-datetime-field-form\n```php\n  // Get a date string suitable for use with entity query.\n  $date = new DrupalDateTime();\n  // This is a date/time from my local timezone.\n  $date = DrupalDateTime::createFromFormat('d-m-Y: H:i A', '28-12-2021: 10:00 AM');\n  $date = new \\Drupal\\Core\\Datetime\\DrupalDateTime(); \n  $date-\u003esetTimezone(new \\DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE));\n  $string = $date-\u003eformat(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);\n  \n  // Query datetime database (datetime field).\n  $query = \\Drupal::entityQuery('node')\n  -\u003econdition('type', 'event')\n  -\u003econdition('status', 1)\n  -\u003econdition('field_event_datetime.value', $query_date, '=')\n  -\u003esort('title', 'ASC');\n  $nids = $query-\u003eexecute();\n  $count = count($nids);\n```\n\n### Retrive datetime field value from node\n@see https://github.com/selwynpolit/d9book/tree/main/web/modules/custom/date_examples\n\n```php\n$event_node = Node::load(1);\ndump($event_node-\u003efield_event_datetime-\u003edate-\u003eformat('m/d/y g:i a', ['timezone'=\u003e'Africa/Cairo']));\ndump($event_node-\u003efield_event_datetime-\u003edate-\u003eformat('m/d/y g:i A', ['timezone'=\u003e'Africa/Cairo']));\ndump($event_node-\u003efield_event_datetime-\u003edate-\u003eformat('F j, Y', ['timezone'=\u003e'Africa/Cairo']));\ndump($event_node-\u003efield_event_datetime-\u003edate-\u003eformat('g:i A', ['timezone'=\u003e'Africa/Cairo']));\n```\n\n\n### DateTime Object\n\n```php\nuse Drupal\\Core\\Datetime\\DrupalDateTime;\n\n   //Convert Timestamp to Drupal DateTime\n   $drupalDateTime = DrupalDateTime::createFromTimestamp($row-\u003ecreated);\n\n   print $drupalDateTime-\u003eformat('r');\n  //Will return \"Wed, 13 Oct 2021 17:40:39 +0300\"\n\n   print $drupalDateTime-\u003e__toString()\n  //Will return 2021-10-13 17:40:39 Europe/Athens\n\n  print $drupalDateTime-\u003eformat('Y-m-d H:i:s')\n  //Will return \"2021-10-13 17:40:39\"\n\n  print $drupalDateTime-\u003eformat('Y-m-d H:i:s P')\n  //Will return \"2021-10-13 17:40:39 +03:00\"\n```\n\n### Set datetime-local html default value\n\n```html\n\u003cdiv class=\"form-group\"\u003e\n  \u003clabel for=\"\"\u003eموعد الاختبار\u003c/label\u003e\n  \u003c?php $datetime = new DateTime($row['start_date']); ?\u003e\n  \u003cinput\n    type=\"datetime-local\"\n    class=\"form-control\"\n    name=\"start_date\"\n    value=\"\u003c?= $datetime-\u003eformat('Y-m-d\\TH:i:s'); ?\u003e\"\n    required\n  /\u003e\n\u003c/div\u003e\n```\n\n### How to Change Date Format from UTC Timezone to Any Required Timezone\n\nIn Drupal, usually the date field value is saved in the database in UTC timezone format.\nOne of our requirements for a project was to show the date in the site's timezone format.\nSo we generated a general function to convert date in UTC timezone to any required timezone and format it.\nJust use the below function to convert date in UTC timzone to a given timezone and the format date using a valid timestamp.\n\n```php\n/**\n * Function to get date/time on user's timezone\n * @param  int $timestamp\n *  Timestamp to be converted to date\n * @param string timezone\n *  Timezone to which date is to be converted\n * @param  string $format\n *  Format to which date to convert\n * @return string\n *  Formatted date.\n */\nfunction get_date_on_given_timezone($timestamp, $new_timezone, $format = 'd/m/Y H:i:s') {\n  if (!empty($timestamp)) {\n    // Database timezone.\n    $db_timezone = 'UTC';\n    $date_object = new DateObject($timestamp, new DateTimeZone($db_timezone));\n    // Convert from the database time zone to site's time zone.\n    $date_object-\u003esetTimezone(new DateTimeZone($new_timezone));\n    $new_date = date_format_date($date_object, 'custom', $format);\n    return $new_date;\n  }\n}\n```\n\n## User\n\n### Drupal 8 Current User Object, useful methods, and what they return\n\n```php\nget current user in Drupal 8\n\n$current_user = \\Drupal::currentUser();\n\n$uid = $current_user-\u003eid();\n// It returns user id of current user.\n\n$user_mail = $current_user-\u003egetEmail();\n// It returns user email id.\n\n$user_display_name = $current_user-\u003egetDisplayName();\n// It returns user display name.\n\n$user_account_name = $current_user-\u003egetAccountName()\n// It returns user account name.\n\n$user_roles = $current_user-\u003egetRoles();\n// It returns array of current user has.\n\n$current_user-\u003eisAnonymous();\n// It returns true or false.\n\n$current_user-\u003eisAuthenticated();\n// It returns true or false.\n\n$current_user-\u003egetLastAccessedTime();\n// It returns the timestamp of the last logged-in time for this user\n```\n\n### Check if the current user is an admin.\n\n```php\n$user = \\Drupal::currentUser()-\u003egetRoles();\n  if(!in_array(\"administrator\", $user) \u0026\u0026 $form_id == 'user_form') {\n   unset($form['account']);\n  }\n```\n\n### Drupal 8 programmatically block and unblock a user\n\n```php\n/**  @var \\Drupal\\user\\UserInterface $user */\n$user = \\Drupal\\user\\Entity\\User::load(USER_ID_HERE);\n$user-\u003eblock();\n// $user-\u003eactivate();\n$user-\u003esave();\n```\n\n### Code snippet that can be used to Log in user programmatically in Drupal 8\n\n```php\nuse Drupal\\user\\Entity\\User;\nuse Symfony\\Component\\HttpFoundation\\RedirectResponse;\n\n\n$user = User::create([\n  'name' =\u003e $userEmail,\n  'mail' =\u003e $userEmail,\n  'pass' =\u003e $password,\n  'status' =\u003e 1,\n]);\nuser_login_finalize($user);\n$user_destination = \\Drupal::destination()-\u003eget();\n$response = new RedirectResponse($user_destination);\n$response-\u003esend();\n```\n\n[Drupal: How to inject a Service into a Class (Controller, Form, Plugin Block, etc) and why not into another service Class](https://pixelthis.gr/content/drupal-8-how-inject-service-class-controller-form-plugin-block-etc-and-why-not-another)\n\n### Profile Module\n\n```php\n// Load profile by user id and profile type.\n $profile = \\Drupal::entityTypeManager()\n        -\u003egetStorage('profile')\n        -\u003eloadByProperties([\n          'uid' =\u003e $doctor_id,\n          'type' =\u003e 'doctor_profile',\n        ]);\n // Get filed data.\n $hcp_profile = reset($hcp_profiles);\n $address = $hcp_profile-\u003eget('field_user_address')-\u003egetValue();\n //Or\n $full_name = $profile-\u003efield_full_name-\u003evalue;\n```\n\n### Reset user password using uid\n\n```php\npublic function restPass()\n  {\n    $user = \\Drupal\\user\\Entity\\User::load(85);\n    kint($user);\n    die();\n    $user-\u003esetPassword('admin');\n    $user-\u003esave();\n    return [\n      '#type' =\u003e 'markup',\n      '#markup' =\u003e 'Done'\n    ];\n  }\n```\n\n### Get user url\n\n```php\n$variables['user_url'] = Url::fromRoute('entity.user.canonical', ['user' =\u003e $account-\u003eid()])-\u003esetAbsolute()-\u003etoString();\n```\n\n## Node\n\n### How to programmatically update an entity reference field\n@see https://stefvanlooveren.me/blog/how-programmatically-update-entity-reference-field-drupal-8\n\n### Render node body field.\n```php\n$body = \\Drupal\\Component\\Utility\\Unicode::truncate(preg_replace('/[^\\w$\\x{0080}-\\x{FFFF}]+/u', ' ',strip_tags($node-\u003eget('body')-\u003evalue) ), 200, true, true);\n```\n### Render a node\n\nOn drupal 8 every elements (almost) are an entity, as any entity you can render a node.\n\n@see http://www.drupal8.ovh/en/tutoriels/339/render-a-node-or-an-entity\n\n```php\n$nid = 1;\n$entity_type = 'node';\n$view_mode = 'teaser';\n$view_builder = \\Drupal::entityTypeManager()-\u003egetViewBuilder($entity_type);\n$storage = \\Drupal::entityTypeManager()-\u003egetStorage($entity_type);\n$node = $storage-\u003eload($nid);\n$build = $view_builder-\u003eview($node, $view_mode);\n$output = render($build);\n```\n\n```php\n// Note : you can also use if you don't want to use different entity types.\n$node = Node::load($nid);\n```\n\n### Get node field value from html scope\n\n```php\nfunction hook_preprocess_html(\u0026$variables) {\n  // If current page is a node full page.\n  $node = \\Drupal::request()-\u003eattributes-\u003eget('node');\n  if ($node) {\n    // Get entity reference field entities and loop.\n    $node_paragraphs = $node-\u003eget('field_paragraphs')-\u003ereferencedEntities();\n\n    foreach ($node_paragraphs as $entity) {\n      // Check entity type and for a not empty field.\n      if ($entity-\u003egetType() === \"card\" \u0026\u0026 !($entity-\u003eget('field_media')-\u003eisEmpty())) {\n        // Add body class.\n        $variables['attributes']['class'][] = \"has-intro-banner\";\n      }\n    }\n  }\n}\n```\n\n### Get current node id\n\n```php\n$node = \\Drupal::routeMatch()-\u003egetParameter('node');\nif ($node instanceof \\Drupal\\node\\NodeInterface) {\n  $nid = $node-\u003eid();\n}\n```\n\n### Get decrypted field values during entity insert/update hook\n\n\u003e The following explains the situation on a `foo` node when attempting to get the value of the text field  \n\u003e `field_bar` during a form-alter, a node pre-save, a node insert, and a node update:\n\n```php\n/**\n * Implements hook_form_BASE_FORM_ID_alter().\n *\n * Alter the edit Foo node form.\n */\nfunction mymodule_form_node_foo_edit_form_alter(\u0026$form, FormStateInterface $form_state, $form_id) {\n  /**  @var \\Drupal\\node\\Entity\\Node $foo_node */\n  $foo_node = $form_state-\u003egetFormObject()-\u003egetEntity();\n  // Value 1 is correct.\n  $bar_value_1 = $foo_node-\u003efield_bar-\u003egetString();\n  // Value 2 is correct.\n  $bar_value_2 = $foo_node-\u003efield_bar-\u003egetValue();\n  // Value 3 is correct.\n  $bar_value_3 = $foo_node-\u003efield_bar[0]-\u003evalue;\n  // Value 4 is correct.\n  $bar_value_4 = $foo_node-\u003eget('field_bar')-\u003egetValue();\n}\n\n/**\n * Implements hook_ENTITY_TYPE_presave().\n */\nfunction mymodule_node_presave(EntityInterface $entity) {\n  // Value 1 is correct.\n  $bar_value_1 = $entity-\u003efield_bar-\u003egetString();\n  // Value 2 is correct.\n  $bar_value_2 = $entity-\u003efield_bar-\u003egetValue();\n  // Value 3 is correct.\n  $bar_value_3 = $entity-\u003efield_bar[0]-\u003evalue;\n  // Value 4 is correct.\n  $bar_value_4 = $entity-\u003eget('field_bar')-\u003egetValue();\n}\n/**\n * Implements hook_ENTITY_TYPE_insert().\n */\nfunction mymodule_node_insert(EntityInterface $entity) {\n  // Value 1 returns `[ENCRYPTED]`.\n  $bar_value_1 = $entity-\u003efield_bar-\u003egetString();\n  // Value 2 returns `[ENCRYPTED]`.\n  $bar_value_2 = $entity-\u003efield_bar-\u003egetValue();\n  // Value 3 returns `[ENCRYPTED]`.\n  $bar_value_3 = $entity-\u003efield_bar[0]-\u003evalue;\n  // Value 4 returns `[ENCRYPTED]`.\n  $bar_value_4 = $entity-\u003eget('field_bar')-\u003egetValue();\n\n  /* @var $field_encrypt_process_entities \\Drupal\\field_encrypt\\FieldEncryptProcessEntities */\n  $field_encrypt_process_entities = \\Drupal::service('field_encrypt.process_entities');\n  $field_encrypt_process_entities-\u003edecryptEntity($entity);\n\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_1 = $entity-\u003efield_bar-\u003egetString();\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_2 = $entity-\u003efield_bar-\u003egetValue();\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_3 = $entity-\u003efield_bar[0]-\u003evalue;\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_4 = $entity-\u003eget('field_bar')-\u003egetValue();\n}\n\n/**\n * Implements hook_ENTITY_TYPE_update().\n */\nfunction mymodule_node_update(EntityInterface $entity) {\n  // Value 1 returns `[ENCRYPTED]`.\n  $bar_value_1 = $entity-\u003efield_bar-\u003egetString();\n  // Value 2 returns `[ENCRYPTED]`.\n  $bar_value_2 = $entity-\u003efield_bar-\u003egetValue();\n  // Value 3 returns `[ENCRYPTED]`.\n  $bar_value_3 = $entity-\u003efield_bar[0]-\u003evalue;\n  // Value 4 returns `[ENCRYPTED]`.\n  $bar_value_4 = $entity-\u003eget('field_bar')-\u003egetValue();\n\n  /* @var $field_encrypt_process_entities \\Drupal\\field_encrypt\\FieldEncryptProcessEntities */\n  $field_encrypt_process_entities = \\Drupal::service('field_encrypt.process_entities');\n  $field_encrypt_process_entities-\u003edecryptEntity($entity);\n\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_1 = $entity-\u003efield_bar-\u003egetString();\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_2 = $entity-\u003efield_bar-\u003egetValue();\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_3 = $entity-\u003efield_bar[0]-\u003evalue;\n  // Value is STILL `[ENCRYPTED]`.\n  $bar_value_4 = $entity-\u003eget('field_bar')-\u003egetValue();\n}\n```\n\n### Create node programmatically\n\n```php\nTry this Code in MigrateContentController:\n\n\u003c?php\n\nnamespace Drupal\\migrate_contents\\Controller;\nuse Drupal\\taxonomy\\Entity\\Term;\nuse Drupal\\Core\\Controller\\ControllerBase;\nuse Drupal\\node\\Entity\\Node;\n\nclass MigrateContentController extends ControllerBase {\n\n function migrateContent() {\n $updated = 0;\n $data = array(\n   'type' =\u003e 'ip_range',\n   'title' =\u003e '192.168.7.100/24',\n   'field_ip_range_gw' =\u003e '192.168.7.100',\n   'field_ip_range_hidden' =\u003e '',\n   'field_ip_range_blocked' =\u003e '192.168.7.200',\n   'field_ip_range_access_type' =\u003e 'Blocked',\n   'field_ip_threshold' =\u003e '20',\n   'field_ip_range_sec_zone' =\u003e 'C2',\n   'field_ip_range_vlan_name' =\u003e 'Network58',\n   'field_ip_range_vlan_tag' =\u003e '4054',\n   'field_ip_range_comment' =\u003e 'Ip ranges from 192.168.7.100 to 192.168.7.255',\n );\n $node = Node::create($data);\n $node-\u003esave();\n $updated++;\n\n return array(\n   '#markup' =\u003e $updated,\n );\n }\n}\n```\n\n### Rendering fields\n\n@see https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet\n@see Long answer https://www.computerminds.co.uk/articles/rendering-drupal-8-fields-right-way\n\n```php\n$node-\u003efield_my_thing-\u003eget(0)-\u003eview();\n\n$node-\u003efield_my_thing-\u003eview();\n\n$node-\u003efield_my_thing-\u003eview('teaser');\n\n$node-\u003efield_my_thing-\u003eview([\n  'type' =\u003e 'image',\n  'label' =\u003e 'hidden',\n  'settings' =\u003e array(\n    'image_style' =\u003e 'larger_thumbnail',\n    'image_link' =\u003e 'content',\n  ),\n]);\n```\n\n## Form\n\nRender form in twig template\n@see https://www.developersdocs.com/blog/drupal-8-theming-define-custom-template-file-form\n\n### Add cancel button to form\n```php\n  // Add cancel button to form.\n  $form['actions']['cancel'] = [\n    '#type' =\u003e 'submit',\n    '#weight' =\u003e 999,\n    '#value' =\u003e t('Cancel'),\n    '#submit' =\u003e ['redirect_to_action'],\n    '#limit_validation_errors' =\u003e [],\n    '#attributes' =\u003e [\n      'class' =\u003e ['btn-cancel']\n    ]\n  ];\n/**\n * Cancel form.\n *\n * @param array $form\n * @param \\Drupal\\Core\\Form\\FormStateInterface $form_state\n */\nfunction redirect_to_action(array \u0026$form, FormStateInterface $form_state): void {\n  $form_state-\u003esetRedirect('\u003cfront\u003e');\n}\n```\n\n### Redirect after login\n\n```php\nuse Drupal\\Core\\Form\\FormStateInterface;\nuse Drupal\\Core\\Url;\n\n/**\n * Implements hook_form_FORM_ID_alter().\n */\nfunction MYCUSTOMMODULE_form_user_login_form_alter(\u0026$form, FormStateInterface $form_state, $form_id) {\n  $form['#submit'][] = 'MYCUSTOMMODULE_user_login_form_submit';\n}\n\n/**\n * Custom submit handler for the login form.\n */\nfunction MYCUSTOMMODULE_user_login_form_submit($form, FormStateInterface $form_state) {\n  $url = Url::fromRoute('/your/destination/path');\n  $form_state-\u003esetRedirectUrl($url);\n}\n```\n\n### Code snippet that can help you to get field values in hook_form_alter in Drupal 8.\n\nExample of entity reference field:\n\n```php\n$form['field_name']['widget'][0]['target_id'][\"#value\"]\n```\n\nPHP\nExample of text field:\n\n```php\n$form['field_name']['widget'][\"#value\"]\n```\n\n### How to use ConfirmFormBase to confirm the action of delete nodes in drupal 8.\n\n\u003e \u003chttps://codimth.com/blog/web/drupal/how-use-confirmformbase-confirm-action-delete-nodes-drupal-8\u003e\n\n### Save config form value\n\n```php\n/**\n * {@inheritdoc}\n */\npublic function submitForm(array \u0026$form, FormStateInterface $form_state) {\n  parent::submitForm($form, $form_state);\n  $config = $this-\u003econfig(self::CONFIG_SETTINGS);\n  $skip = [\"submit\", \"form_build_id\", \"form_token\", \"form_id\", \"op\"];\n  foreach ($form_state-\u003egetValues() as $key =\u003e $value) {\n    if (!in_array($key, $skip)) {\n      $config-\u003eset($key, $value);\n    }\n  }\n  $config-\u003esave();\n}\n```\n\n## Taxonomy\n\n### How to filter for the top level of a taxonomy in view\n@see (https://www.drupal.org/forum/support/post-installation/2010-07-22/how-to-filter-for-the-top-level-of-a-taxonomy-in-view)\n\n1. Filter \u003e Parent term \u003eis equal to\n2. Leave it blank.\n\n### Get entity reference field (taxonomy) value\n\n```php\n$termId = $relationshipEntities['profile']-\u003eget('field_job_title')-\u003etarget_id;\n$term = \\Drupal::entityTypeManager()-\u003egetStorage('taxonomy_term')-\u003eload($termId);\n$termValue = $term-\u003eget('field_public')-\u003evalue;\n```\n\n### Get all taxonomy terms from node\n\n```php\nfunction hook_preprocess_node(\u0026$variables) {\n\n  //make sure you have Devel module installed, then you can use ksm() to explore variables\n  //ksm($variables['node']);\n\n  if ($variables['node']-\u003ehasField('field_permit_city')) {\n    //this will give you the referenced terms on the node as objects\n    $term_objects = $variables['node']-\u003eget('field_permit_city')-\u003ereferencedEntities();\n    $term_labels = [];\n    foreach ($term_objects as $term_object) {\n      print $term_object-\u003eid(); //the id of the term\n      print $term_object-\u003elabel(); //the term title\n      $term_labels[] = $term_object-\u003elabel(); //build an array of term labels\n    }\n    //send an array of term titles over to the node twig template\n    $variables['my_custom_template_variable'] = $term_labels;\n  }\n}\n```\n\n### Load nodes by term id\n\n```php\n$termIds = [3,56,456];\n $nodes = \\Drupal::entityTypeManager()-\u003egetStorage('node')-\u003egetQuery()\n -\u003elatestRevision()\n -\u003econdition('field_tags', $termIds)\n -\u003eexecute();\n```\n\n### Get taxonomy term from node using entity refrence\n\n```php\n$term_name = $node\n-\u003eget('field_subspecialty_category')\n-\u003ereferencedEntities()[0]\n-\u003egetTranslation($lang)\n-\u003elabel();\n```\n\n## Block\n\n### Render Block Programtically.\n```php\n/**\n * Render block.\n *\n * @param string $blockName\n *   Block machine name.\n *\n * @return string|array\n */\nfunction yourModule_render_block(string $blockName): string|array {\n  $block = Block::load($blockName);\n  if ($block) {\n    return \\Drupal::entityTypeManager()\n      -\u003egetViewBuilder('block')\n      -\u003eview($block);\n  }\n  return '';\n}\n```\n### Set block class for custom block bundles.\n\n@see https://www.drupal.org/node/2724333\n\n```php\n/**\n * Implements hook_preprocess_block().\n */\n\nfunction hops_preprocess_block(\u0026$variables) {\n  // Add class for a specific block id.\n  $block_id = $variables['elements']['#id'];\n  switch ($block_id) {\n    case '':\n      $variables['attributes']['class'][] = '';\n      break;\n\n    default:\n      break;\n  }\n\n  if (isset($variables['elements']['content']['#block_content'])) {\n    $variables['attributes']['class'][] = 'block--'. $variables['elements']['content']['#block_content']-\u003ebundle();\n  }\n}\n```\n\n### Ways to find the block ID\n\n```bash\ndrush ev \"print_r(array_keys(\\Drupal::service('plugin.manager.block')-\u003egetDefinitions()));\"\n```\n\n\u003e If you know part of the ID, you can search for it by adding grep to the end. For example, I have a block that I know has “profile” in the ID, but I don’t know the full ID. I can find it my using this command:\n\n```bash\ndrush ev \"print_r(array_keys(\\Drupal::service('plugin.manager.block')-\u003egetDefinitions()));\" | grep profile\n```\n\n### Disable block caching in drupal 8\n\n```php\nclass MYCUSTOMBLOCK extends BlockBase {\n  /**\n   * {@inheritdoc}\n   */\n    public function build() {\n        return array(\n            '#markup' =\u003e \"\"\n        );\n    }\n    /**\n     * {@inheritdoc}\n     */\n    public function getCacheMaxAge() {\n        return 0;\n    }\n}\n```\n\n### How can I programmatically display a block?\n\n@see https://drupal.stackexchange.com/questions/171686/how-can-i-programmatically-display-a-block\n\n### Content Blocks\n\n```php\n$bid = ??? // Get the block id through config, SQL or some other means\n$block = \\Drupal\\block_content\\Entity\\BlockContent::load($bid);\n$render = \\Drupal::entityTypeManager()-\u003e\n  getViewBuilder('block_content')-\u003eview($block);\nreturn $render;\n```\n\n### Plugin blocks\n\n```php\n$block_manager = \\Drupal::service('plugin.manager.block');\n// You can hard code configuration or you load from settings.\n$config = [];\n$plugin_block = $block_manager-\u003ecreateInstance('system_breadcrumb_block', $config);\n// Some blocks might implement access check.\n$access_result = $plugin_block-\u003eaccess(\\Drupal::currentUser());\n// Return empty render array if user doesn't have access.\n// $access_result can be boolean or an AccessResult class\nif (is_object($access_result) \u0026\u0026 $access_result-\u003eisForbidden() || is_bool($access_result) \u0026\u0026 !$access_result) {\n  // You might need to add some cache tags/contexts.\n  return [];\n}\n$render = $plugin_block-\u003ebuild();\n// In some cases, you need to add the cache tags/context depending on\n// the block implemention. As it's possible to add the cache tags and\n// contexts in the render method and in ::getCacheTags and\n// ::getCacheContexts methods.\nreturn $render;\n```\n\n#### Config entities\n\n```php\n$block = \\Drupal\\block\\Entity\\Block::load('config.id');\n$render = \\Drupal::entityTypeManager()\n  -\u003egetViewBuilder('block')\n  -\u003eview($block);\nreturn $render;\n```\n\n## Views\n\n### Make a view to render content based on each category\n@see https://drupal.stackexchange.com/questions/98881/how-to-display-multiple-products-under-each-category-in-a-views-grid\n\n### Views Tutorials\n@see https://drupal-tools.web.cern.ch/how-to/view-tutorials\n\n### Make custom filter\n@see https://tech.axelerant.com/how-to-use-hookviewsdataalter-in-drupal-8\n\n### How to load a view via ajax without breaking ajax functionality?\n@see https://pixelthis.gr/content/drupal8-how-load-view-ajax-without-breaking-ajax-functionality\n\n### Render a profile view\n\n```php\n  $uid = $variables['user']-\u003eid();\n  $args = [$uid];\n  $view = \\Drupal\\views\\Views::getView('profiles');\n  if (is_object($view)) {\n    $view-\u003esetArguments($args);\n    $view-\u003esetDisplay('user_view');\n    $view-\u003epreExecute();\n    $view-\u003eexecute();\n\n    // @see https://drupal.stackexchange.com/questions/219475/get-result-view-with-formatter-programmattically\n    $profileFields = [];\n    foreach ($view-\u003eresult as $rid =\u003e $row) {\n      foreach ($view-\u003efield as $fid =\u003e $field ) {\n        $profileFields[$rid][$fid . '-value'] = $field-\u003egetValue($row);\n        $profileFields[$rid][$fid . '-render'] = $field-\u003erender($row);\n        $profileFields[$rid][$fid] = $field-\u003eadvancedRender($row);\n      }\n    }\n    $variables['profileFields'] = $profileFields;\n  }\n```\n\n## Database\n\n### Work with the database in Drupal\n@see https://drupaloutsourcing.com/blog/work-database-drupal-8\n\n### How do I specify in which database my schema should be created?\n```php\n\u003c?php\n\n/**\n * @file\n * Install, update and uninstall functions for the d8module module.\n */\n\nfunction d8module_schema_otherdb() {\n  $schema['mytable'] = array(\n    'description' =\u003e 'My table description',\n    'fields' =\u003e array(\n      'myfield' =\u003e array(\n        'description' =\u003e 'My field description',\n        'type' =\u003e 'serial',\n        'size' =\u003e 'medium',\n        'not null' =\u003e TRUE,\n        'unsigned' =\u003e TRUE,\n      ),\n    ),\n    'primary key' =\u003e array('myfield'),\n  );\n  return $schema;\n}\n\n/**\n * Implements hook_install().\n */\nfunction d8module_install() {\n  \\Drupal\\Core\\Database\\Database::setActiveConnection('otherdb');\n  $connection = \\Drupal\\Core\\Database\\Database::getConnection();\n\n  $schema = d8module_schema_otherdb();\n  foreach ($schema as $name =\u003e $table) {\n    $connection-\u003eschema()-\u003ecreateTable($name, $table);\n  }\n\n  \\Drupal\\Core\\Database\\Database::setActiveConnection();\n}\n\n/**\n * Implements hook_uninstall().\n */\nfunction d8module_uninstall() {\n  \\Drupal\\Core\\Database\\Database::setActiveConnection('otherdb');\n  $connection = \\Drupal\\Core\\Database\\Database::getConnection();\n\n  $schema = d8module_schema_otherdb();\n  foreach ($schema as $name =\u003e $table) {\n    $connection-\u003eschema()-\u003edropTable($name);\n  }\n\n  \\Drupal\\Core\\Database\\Database::setActiveConnection();\n}\n```\n\n### Entity Query: Get all the node entities between a daterange\n@see https://pixelthis.gr/content/entity-query-get-all-node-entities-between-daterange\n\n### Drop custom table from database.\n\n```php\n// Using this hook in file mymodule.install\nfunction hook_uninstall(){\n    $table = 'your_table_name';\n    $schema = Database::getConnection()-\u003eschema();\n    $schema-\u003edropTable($table);\n}\n```\n\n### Load node by entityQuery\n\n```php\n$query = \\Drupal::entityQuery('node')\n    -\u003econdition('status', 1)\n    -\u003econdition('changed', REQUEST_TIME, '\u003c')\n    -\u003econdition('title', 'cat', 'CONTAINS')\n    -\u003econdition('field_tags.entity.name', 'cats');\n$nids = $query-\u003eexecute();\n```\n\n### DATABASE OPERATIONS\n\n### Now we can checkout the select, update, and delete operations in Drupal 8. For a field selection use.\n\n```php\n$query = \\Drupal::database()-\u003eselect('table_name', 'alias')\n  -\u003efields('alias', ['field1', field2])\n  -\u003econdition('field3', $condition);\n$results = $query-\u003eexecute();\nwhile ($content = $results-\u003efetchAssoc()) {\n  // Operations using $content.\n}\n```\n\n\u003e For a single field selection we can use `$last_paper_id = $last_paper-\u003efetchField();`\n\n### For update query execution in Drupal 8, we can use.\n\n```php\n$table = 'table_name';\n\\Drupal::database()-\u003eupdate($table)\n  -\u003efields(array('field1' =\u003e $value1, 'field2' =\u003e $value2))\n  -\u003econdition('field3', $condition1)\n  -\u003econdition('field4', $condition2)\n  -\u003eexecute();\n```\n\n### For content deletion.\n\n```php\n$query = \\Drupal::database()-\u003edelete('table_name');\n  $query-\u003econdition('field1', $condition1);\n  $query-\u003econdition('field2', $condition2);\n  $query-\u003eexecute();\n```\n\n\u003e Now checkout other database statements in Drupal 8 from this [Link](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Connection.php/class/Connection/8.2.x)\n\n### Select\n\n### For retrieving single value from Table###\n\n```php\n/**\n * select table 'node_field_data' from database\n * select field 'title' fropm table 'node_field_data'\n * get data for content type = ‘page’\n * Limit query and only fetch one entry\n */\n$getSingleValue = \\Drupal::database()-\u003eselect('node_field_data', 'nfd');\n$getSingleValue-\u003eaddField('nfd', 'title');\n$getSingleValue-\u003econdition('nfd.type', 'page');\n$getSingleValue-\u003erange(0, 1);\n$title = $getSingleValue-\u003eexecute()-\u003efetchField();\n```\n\n### For retrieving single row from Table###\n\n```php\n/**\n * select table 'node_field_data' from database\n * select fields ('nid', 'title', 'status' from table 'node_field_data'\n * get data for content type = ‘page’\n * Limit query and only fetch one entry\n */\n$getValues = \\Drupal::database()-\u003eselect('node_field_data', 'nfd');\n$getValues-\u003efields('nfd', ['nid', 'title', 'status']);\n$getValues-\u003econdition('nfd.type', 'page');\n$getValues-\u003erange(0, 1);\n$singleRow = $getValues-\u003eexecute()-\u003efetchAssoc();\n```\n\n### For retrieving single row from Table using Operator (‘IN’)###\n\n```php\n/**\n * select table 'node_field_data' from database\n * select fields ('nid', 'title', 'status' from table 'node_field_data'\n * get data for content type IN ‘page’\n * Limit query and only fetch one entry\n */\n$getValues = \\Drupal::database()-\u003eselect('node_field_data', 'nfd');\n$getValues-\u003efields('nfd', ['nid', 'title', 'status']);\n$getValues-\u003econdition('nfd.type', 'page' , 'IN');\n$getValues-\u003erange(0, 1);\n$singleRow = $getValues-\u003eexecute()-\u003efetchAssoc();\n```\n\n### With Multiple rows and Table###\n\n```php\n/**\n * select table 'node_field_data' from database\n * select fields ('nid', 'title', 'status' from table 'node_field_data'\n * INNER join on Table 'users_field_data' and select field 'name' from table\n * get data for content type IN ‘page’\n * fetch all data with 'nid' as key for result\n */\n$content = \\Drupal::database()-\u003eselect('node_field_data', 'nfd');\n$content-\u003efields('nfd', ['nid', 'title', 'status']);\n$content-\u003eaddField('ufd', 'name');\n$content-\u003ejoin('users_field_data', 'ufd', 'ufd.uid = nfd.uid');\n$content-\u003econdition('nfd.type', 'page');\n$contentData = $content-\u003eexecute()-\u003efetchAllAssoc('nid');\n```\n\n### Update\n\n### For update single row###\n\n```php\n/**\n * Existing table 'node_clinical_trial' has entry\n * 'secondary progressive MS' on ID 5\n * Lets update to 'Multiple Sclerosis' using update\n */\n\n$content = \\Drupal::database()-\u003eupdate('node_clinical_trial', 'nct');\n$content-\u003efields('nct', ['disease' =\u003e 'Multiple Sclerosis']);\n$content-\u003econdition('nct.entity_id', 5);\n$content-\u003eexecute();\n```\n\n### Delete\n\n### For delete single row###\n\n```php\n/**\n * Existing table 'node_clinical_trial'\n * has entry 'diabetes' on ID 6\n * which is not MS type disease\n * Lets delete that entry using delete\n */\n$content = \\Drupal::database()-\u003edelete('node_clinical_trial', 'nct');\n$content-\u003econdition('nct.entity_id', 6);\n$content-\u003eexecute();\n```\n\n### Insert\n\n### For Adding data\n\n```php\n/**\n * Add 'disease' \u0026 'physician' name in Master table\n * 'node_clinical_trial'\n * Use insert\n */\n\n$content = \\Drupal::database()-\u003einsert('node_clinical_trial');\n$content-\u003efields(['disease', 'physician']);\n$content-\u003evalues(['Psoriasis','Dr.Holmes']);\n$content-\u003eexecute();\n```\n\n[How to Add Join in Views Query Alter](https://www.zyxware.com/articles/5725/solved-how-to-add-join-in-views-query-alter)\n\n### Debug Query\n\n```php\n// Debug.\ndump($query-\u003e__toString());\ndump($query-\u003esqlQuery-\u003e__toString());\n```\n\n## Services\n\n### Inject a Service in Drupal 8\n\n\u003e Is a good practice to inject a service whenever is possible.\n\u003e You can verify the service name by\n\u003e Looking at the `Drupal` Static Service Container wrapper class\n\u003e Reading the code on the `Drupal` Class you can find the `httpClient` method:\n\n```php\n/**\n * Returns the default http client.\n *\n * @return \\GuzzleHttp\\Client\n *   A guzzle http client instance.\n */\npublic static function httpClient() {\n  return static::getContainer()-\u003eget('http_client');\n}\n```\n\n### Inject the service\n\n\u003e Now that you know the service name `http_client`\n\u003e Inject into a Class (Controller, Form, Plugin Block, etc)\n\n```php\n /**\n   * Guzzle Http Client.\n   *\n   * @var GuzzleHttp\\Client\n   */\n  protected $httpClient;\n\n /**\n   * Constructs a new Class.\n   *\n   * @param \\GuzzleHttp\\Client $http_client\n   *   The http_client.\n   */\n  public function __construct(\n    Client $http_client\n  ) {\n    $this-\u003ehttpClient = $http_client;\n  }\n\n  /**\n   * {@inheritdoc}\n   */\n  public static function create(ContainerInterface $container) {\n    return new static(\n      $container-\u003eget('http_client')\n    );\n  }\n```\n\n### Inject a service into a service Class\n\n```yml\n// modules/custom/example/example.services.yml\nservices:\n  example.default:\n    class: Drupal\\example\\DefaultService\n    arguments: [\"@http_client\"]\n```\n\n```php\n// modules/custom/example/src/DefaultService.php\n/**\n * GuzzleHttp\\Client definition.\n *\n * @var GuzzleHttp\\Client\n */\nprotected $http_client;\n/**\n * Constructor.\n */\npublic function __construct(Client $http_client) {\n  $this-\u003ehttp_client = $http_client;\n}\n```\n\n## Theme\n\n### Adding suggestions to views and preprocessing them\n@see https://pixelthis.gr/content/drupal-9-adding-suggestions-views-and-preprocessing-them\n\n### How to add html tags (span,div,strong etc) in your Menu Item Title\n@see https://pixelthis.gr/content/drupal-8-how-add-html-tags-spandivstrong-etc-your-menu-item-title\n\n### How to pass the base url to drupalSettings for global access\n```php\n/**\n * Implements hook_page_attachments_alter().\n *\n * @inheritdoc\n */\nfunction your_theme_page_attachments_alter(\u0026$page) {\n  global $base_url;\n  $page['#attached']['drupalSettings']['baseURL'] = $base_url;\n}\n```\n\n### Access views-view-unformatted.html.twig fields.\n\n```twig\n{% if title %}\n \u003ch3\u003e{{ title }}\u003c/h3\u003e\n{% endif %}\n{% for row in rows %}\n {%\n    set row_classes = [\n      default_row_class ? 'views-row',\n    ]\n  %}\n \u003cdiv{{row.attributes.addClass(row_classes)}}\u003e\n  {# {{- row.content -}} #}\n  {{row.content['#row']._entity.title.value}}\n  {{row.content['#row']._entity.field_video_url.value}}\n  {{file_url(row.content['#row']._entity.field_video_thumbnail.entity.uri.value)}}\n \u003c/div\u003e\n{% endfor %}\n```\n\n### Getting Drupal 8 Field Values in Twig\n\n[Article](https://sarahcodes.medium.com/getting-drupal-8-field-values-in-twig-22b80cb609bd)\n\n### Rewrite the output of a field\n\n`$variables[\"items\"][0][\"content\"] = \"\";`\n\n### Provide frontpage variant\n\n```php\ntry {\n  $isFront = \\Drupal::service('path.matcher')-\u003eisFrontPage();\n}\ncatch (Exception $e) {\n  $isFront = FALSE;\n}\n```\n\n## Drush\n\n@see https://www.drupal.org/node/1023440\n\n### EXPORT DATABASE ON LIVE SERVER\n### Drush, use this command, which will include only the structure and not the contents of the cache tables, and gzip-compress.\n\n```bash\ndrush sql:dump --gzip --structure-tables-list=\"cache,cache_*\" --result-file='PATH/TO/BACKUPFILE.sql'\n```\n\n### If you are using MySQL and have access to the command line, use this command after truncating the cache tables (substituting in your site’s database name, user name, and password):\n\n```bash\nmysqldump -u'USERNAME' -p'PASSWORD' DATABASENAME | gzip \u003e PATH/TO/BACKUPFILE.sql.gz\n```\n\n### IMPORT DATABASE ON LIVE SERVER\n### If you are using MySQL and have access to the command line, use this command (substituting in your site’s database name, user name, and password; if you made a gzip-compressed backup file, you will also need to uncompress it first):\n\n```bash\ngunzip \u003c PATH/TO/BACKUPFILE.sql.gz | mysql -u'USERNAME' -p'PASSWORD' DATABASENAME\n```\n\n### If you prefer to use Drush, use this command:\n\n```bash\ndrush sql:query --file='PATH/TO/BACKUPFILE.sql.gz'\n```\n\n\n### Unlock bloqued used\n\n`drush uublk username` to unblock the user\n\n### Taking advantage of Drupal Console debugging capabilities\n\n```bash\ndrupal container:debug\n```\n\nIf you do not want to see the full list of services you can use `| grep http`\n\n```bash\ndrupal container:debug | grep http\n```\n\nBut you may do not know the service name, then I higly recommend you to use peco interactive filtering tool\n\n```bash\ndrupal container:debug | peco | awk -F ' ' '{print $1}' | xargs drupal container:debug\n```\n\nYou can find peco at \u003chttps://github.com/peco/peco\u003e\n\n### Apply Patches with composer in drupal 9.\n\nrun this command to get the module:.\n`composer require cweagans/composer-patches`.\nAdd this to your `composer.json` file:.\n\n```bash\n\"extra\": {\n    \"enable-patching\": true,\n    \"patches\": {\n        ...\n        ...\n     }\n}\n```\n\n### Generate hshad salat `$settings['hash_salt']`\n\n```bash\ndrush php:eval \"echo \\Drupal\\Component\\Utility\\Crypt::randomBytesBase64(55)\"\n```\n\n## Links\n\n@see https://agaric.coop/blog/creating-links-code-drupal-8\n\n```php\nuse Drupal\\Core\\Link;\n$link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' =\u003e 1]);\n```\n\nMore flexibility with URL object\n\n```\nuse Drupal\\Core\\Link;\nuse Drupal\\Core\\Url;\n$link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' =\u003e 1]));\n```\n\nInternal links which have no routes\n\n`$link = Link::fromTextAndUrl('This is a link', Url::fromUri('base:robots.txt'));`\n\nExternal links:\n\n```php\n  use Drupal\\Core\\Url;\n  use Drupal\\Core\\Link;\n  $link = !empty($url) ? Link::fromTextAndUrl($this-\u003et('Newsletter'), Url::fromUri($url, [\n    'attributes' =\u003e [\n      'target' =\u003e '_blank',\n      'class' =\u003e ['button']\n    ],\n  ])) : '';\n  $html_link = $link-\u003etoString();\n```\n\nUsing the data provided by a user\n\n`$link = Link::fromTextAndUrl('This is a link', Url::fromUserInput('/node/1');`\n\nLinking entities.\n\n`$link = Link::fromTextAndUrl('This is a link', Url::fromUri('entity:node/1'));`\n\nDrupal usually expects a render array if you are going to print the link, so the Link object has a method for that\n\n`$link-\u003etoRenderable();`\n\nAdd links inside a t() method.\nNeed to pass the link as a string.\n\n```php\n$link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' =\u003e 1]));\n$this-\u003et('You can click this %link' ['%link' =\u003e $link-\u003etoString()]);\n```\n\n### Re-import Installed Module Configuration Using Drush\n```bash\ndrush config-import --partial --source=modules/custom/\u003cmodule_name\u003e/config/install --yes\n```\n\n## Twig\nAccess `views-view-unformated.html.twig` content.\n```html\n{# taxonomy field #}\n{{ row.content['#row']._entity.field_course_categories.entity.name.value }}\n{{ row.content['#row']._entity.field_name[0].value }}\n{{ view.field.field_name.original_value }} {# working for translations #}\n```\n\n## Paragraphs\n\n### Load paragraph fields values\n```php\n$paragraph = $node-\u003efield_paragraph-\u003egetValue();\n// Loop through the result set.\nforeach ( $paragraph as $element ) {\n  $p = \\Drupal\\paragraphs\\Entity\\Paragraph::load( $element['target_id'] );\n  $text = $p-\u003efield_name-\u003egetValue();\n}\n```\n\n```twig\n{{ drupal_dump(paragraph) }}\n{{ drupal_dump(paragraph.field_button_style) }}\n{{ drupal_dump(paragraph.field_button_style.value) }}\nTo print out single fields I usually use, `{{ paragraph.field_action.value }}`. I think that should also work for you.\n\nIn the case of an entity reference field, you need to use `{{ paragraph.field_action.entity.field.value }}`.\n```\n\n### Paragraph Module\n\n\u003e load the paragraphs content.\n\n```php\n$node  = \\Drupal\\node\\Entity\\Node::load(1);\n$paragraph = $node-\u003efield_paragraph-\u003egetValue();\n// Loop through the result set.\nforeach ( $paragraph as $element ) {\n  $p = \\Drupal\\paragraphs\\Entity\\Paragraph::load( $element['target_id'] );\n  $text = $p-\u003efield_name-\u003egetValue();\n}\n```\n### Suggestion paragraph\n```php\n  // Paragraphs.\n  if ($hook === 'paragraph' \u0026\u0026 !empty($variables['elements']['#paragraph'])) {\n    $paragraph = $variables['elements']['#paragraph'];\n    $node = \\Drupal::routeMatch()-\u003egetParameter('node');\n    if ($node) {\n      $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');\n\n      $suggestions[] = 'paragraph__' . $sanitized_view_mode;\n      $suggestions[] = 'paragraph__' . $paragraph-\u003ebundle() . '__' . $node-\u003ebundle();\n      $suggestions[] = 'paragraph__' . $paragraph-\u003ebundle() . '__' . $node-\u003ebundle() . '__' . $sanitized_view_mode;\n    }\n  }\n```\n\n## General\n[Useful Links](https://github.com/gkapoor121212/drupal9-links)\n\n### import translation file using drush command\n```bash\ndrush locale:import ar sites/default/translation/ar.po --type=customized --override=all -y\n```\n\n### Return access not allowed from theme.\n```php\n/**\n * Implements hook_preprocess_page().\n */\nfunction my_theme_preprocess_page(\u0026$variables) {\n  $current_route_name = \\Drupal::routeMatch()-\u003egetRouteName();\n  $current_user = \\Drupal::currentUser();\n      if (!$current_user-\u003ehasPermission('permission name')) {\n      throw new \\Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException();\n    }\n}\n```\n\n### Make field unique field\n```php\nuse Drupal\\Core\\Entity\\EntityTypeInterface;\n// if you make a field belongs to a node just change $entity_type to 'node'\nfunction hook_entity_bundle_field_info_alter(\u0026$fields, EntityTypeInterface $entity_type, $bundle) {\n  // D8 =\u003e $entity_type-\u003eid()\n  // D9 =\u003e $entity-\u003egetEntityTypeId()\n  if ($entity_type-\u003eid() === 'user') {\n    if (isset($fields['field_user_id'])) {\n      $fields['field_user_id']-\u003eaddConstraint('UniqueField', ['message' =\u003e t('this id is used before with another user')]);\n    }\n  }\n}\n```\n\n### PHP: Get current year seasons, per year not just for the current year\n@see https://pixelthis.gr/content/php-get-current-year-seasons-year-not-just-current-year\n\n\u003e Drupal class =\u003e \u003chttps://api.drupal.org/api/drupal/core%21lib%21Drupal.php/class/Drupal/8\u003e\n\n## DRUPAL CONSOLE\n\n### Installing.\n\n\u003e composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader --sort-packages\n\n### Middlware for redirect issues\n\n```yml\n// module.service.yml\nservices:\n  http_middleware.your_module:\n    class: Drupal\\your_module\\RedirectMiddleware\n    tags:\n      - { name: http_middleware}\n```\n\n```php\n\u003c?php\n\n// Service class.\nnamespace Drupal\\your_module;\n\nuse Symfony\\Component\\HttpFoundation\\Request;\nuse Symfony\\Component\\HttpFoundation\\Response;\nuse Symfony\\Component\\HttpKernel\\HttpKernelInterface;\nuse Symfony\\Component\\HttpFoundation\\RedirectResponse;\nuse Drupal\\Core\\Routing\\TrustedRedirectResponse;\nuse Drupal\\Core\\Url;\n\n/**\n * Executes redirect before the main kernel takes over the request.\n */\nclass RedirectMiddleware implements HttpKernelInterface {\n\n  /**\n     * The wrapped HTTP kernel.\n     *\n     * @var \\Symfony\\Component\\HttpKernel\\HttpKernelInterface\n     */\n  protected $httpKernel;\n\n  /**\n     * The redirect URL.\n     *\n     * @var \\Symfony\\Component\\HttpFoundation\\RedirectResponse\n     */\n  protected $redirectResponse;\n\n  /**\n     * Constructs a RedirectMiddleware\n     * object.\n     *\n     * @param \\Symfony\\Component\\HttpKernel\\HttpKernelInterface $http_kernel\n     *   The decorated kernel.\n     */\n  public function __construct(HttpKernelInterface $http_kernel) {\n        $this-\u003ehttpKernel = $http_kernel;\n      }\n\n  /**\n     * {@inheritdoc}\n     */\n  public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = TRUE) {\n        $response = $this-\u003ehttpKernel-\u003ehandle($request, $type, $catch);\n        return $this-\u003eredirectResponse ?: $response;\n  }\n\n  /**\n     * Stores the requested redirect response.\n     *\n     * @param \\Symfony\\Component\\HttpFoundation\\RedirectResponse|null $redirectResponse\n     *   Redirect response.\n     */\n  public function setRedirectResponse(?RedirectResponse $redirectResponse) {\n        $this-\u003eredirectResponse = $redirectResponse;\n  }\n\n}\n\n// USING\n$middleware = \\Drupal::service('http_middleware.your_module');\n$response = new RedirectResponse(Url::fromUserInput($url)-\u003etoString());\n$middleware-\u003esetRedirectResponse($response);\n```\nOR\n```php\nuse Drupal\\Core\\Session\\AccountInterface;\nuse Drupal\\Core\\Url;\n\n/**\n * Implements hook_user_login().\n */\nfunction greenacorn_user_login(AccountInterface $account) {\n  $roles = $account-\u003egetRoles();\n  // user.reset.login == reset\n  // user.login == login\n  $route_name = \\Drupal::routeMatch()-\u003egetRouteName();\n  if ($route_name != 'user.reset.login' \u0026\u0026 in_array('client', $roles)) {\n    $destination = Url::fromUserInput('/my-issues')-\u003etoString();\n    \\Drupal::service('request_stack')-\u003egetCurrentRequest()-\u003equery-\u003eset('destination', $destination);\n  }\n}\n```\n\n### Render view programitcally\n\n```php\n $view = \\Drupal\\views\\Views::getView('geographical_statistics');\n// Execute the view.\n$view-\u003eexecute();\n$view_result = $view-\u003eresult;\nforeach ($view_result as $obj){\n// Code...\n}\n```\n\n### Show error messages\n\n```php\n$config['system.logging']['error_level'] = 'verbose';\n```\n\n### Show twitter timeline\n\n```html\n\u003ca class=\"twitter-timeline\" href=\"https://twitter.com/{field_twitterhandle}\"\u003e\n  Tweets by {field_name}\u003c/a\n\u003e\n\u003cscript\n  async\n  src=\"https://platform.twitter.com/widgets.js\"\n  charset=\"utf-8\"\n\u003e\u003c/script\u003e\n```\n\n### Install drupal console\n\n```bash\n$composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader --sort-packages --no-update --dev\n$composer update drupal/console\n```\n\n### Fast site install with lando \u0026 config management\n\n```bash\n$ lando drush site-install standard --account-name=admin --account-pass=admin --db-url='mysql://drupal8:drupal8@database/drupal8' --site-name=Test site\n# Get uuid from source\n$ drush config-get \"system.site\" uuid\n# @see https://drupal.stackexchange.com/questions/150481/how-can-i-import-the-configuration-on-a-different-site/217126\n# Set local uuid\n$ drush config-set \"system.site\" uuid \"fjfj34-e3bb-2ab8-4d21-9100-b5etgetgd99d5\"\n```\n\n### Import drupal 8 configuration into a fresh install website\n\n_@see https://www.dannyenglander.com/blog/drupal-8-development-how-import-existing-site-configuration-new-site_\n\n```bash\n$ drush cget system.site uuid\n'system.site:uuid': bfb11978-d1a3-4eda-91fb-45decf134e25\n$ drush cset system.site uuid bfb11978-d1a3-4eda-91fb-45decf134e25\n$ drush ev '\\Drupal::entityManager()-\u003egetStorage(\"shortcut_set\")-\u003eload(\"default\")-\u003edelete();'\n```\n\n### Install `Drupal Console`\n@see https://drupalconsole.com/docs/en/\n```bash\n$ composer require drupal/console:~1.0 --prefer-dist --optimize-autoloader\n$ composer update drupal/console --with-dependencies\n```\n### Testing\n\n@todo description\n\n```bash\n~/Sites/siteName ᐅ vendor/bin/dcr web/themes/contrib/file\nphpcs --standard=Drupal dir/file\nphpcbf --standard=Drupal dir/file\n~/Sites/siteName/web ᐅ eslint dir/file.js\n```\n\n### Setting up a local developent website standard workflow\n@see https://pixelthis.gr/content/drupal-8-setting-local-developent-website-standard-workflow)\n\n### Drupal with Docker\n@see https://medium.com/drupal-stories/drupal-dev-environment-on-docker-3c795f2ac7aa\n\n### Change breadcrunb\n```php\n/**\n * Implement hook_system_breadcrumb_alter().\n *\n * @param \\Drupal\\Core\\Breadcrumb\\Breadcrumb $breadcrumb\n * @param \\Drupal\\Core\\Routing\\RouteMatchInterface $route_match\n * @param array $context\n *\n * @return void\n */\nfunction my_module_system_breadcrumb_alter(\\Drupal\\Core\\Breadcrumb\\Breadcrumb \u0026$breadcrumb, \\Drupal\\Core\\Routing\\RouteMatchInterface $route_match, array $context) {\n  if ($breadcrumb !== NULL) {\n    $current_route_name = \\Drupal::routeMatch()-\u003egetRouteName();\n    $links = $breadcrumb-\u003egetLinks();\n    if ($current_route_name === 'entity.user.edit_form') {\n      array_pop($links);\n      $breadcrumb = new \\Drupal\\Core\\Breadcrumb\\Breadcrumb();\n      $breadcrumb-\u003esetLinks($links);\n    }\n  }\n}\n```\n\n### Diable cache in local development\n@see https://www.drupal.org/node/2598914\n\n### Disable password experation\n```php\n  $u = \\Drupal\\user\\Entity\\User::load(1);\n  $u-\u003eset(\"field_password_expiration\", \"0\");\n  $u-\u003esave();\n```\n\n### Replace file after uploaded\n```php\n    try {\n      $values = $form_state-\u003egetValues();\n      $files = $values['my_file'];\n      /** @var \\Drupal\\file\\Entity\\File $file */\n      $file = File::load($files[0]);\n      // Gets content from file.\n      $file_real_path = \\Drupal::service('file_system')-\u003erealpath($file-\u003egetFileUri());\n      $file_contents = file_get_contents($file_real_path);\n      // Saves new file with fixed name and replaces any existing file.\n      \\Drupal::service('file.repository')\n        -\u003ewriteData($file_contents, 'private://my_files/import.csv', FileSystemInterface::EXISTS_REPLACE);\n      // Deletes the uploaded file.\n      $file-\u003edelete();\n  \n    } catch (\\Throwable $e) {\n      \\Drupal::messenger()-\u003eaddError('check logs messages');\n    }\n```\n\n\n---------------------------------------------------------\nSITE BUILDING CASES\n---------------------------------------------------------\n1. Create parent terms based on parent id @see (https://www.youtube.com/watch?v=v5s6DPc23cI)\n\n### Step 1: Create a View to Display Nodes with Taxonomy Terms\nCreate a View for Content:\n\nGo to Structure \u003e Views \u003e Add view.\nName your view (e.g., \"Node Taxonomy Hierarchy\").\nSet Show to Content (since you want to display nodes and their terms).\nSet Filter by content type to limit the view to the relevant content type if needed.\nSet the Display Type:\n\nChoose Unformatted list or Table based on your preference.\nSelect Create a Page if you want this view to be accessible via a URL route.\n\n### Step 2: Add Relationships to Include Taxonomy Terms and Their Parents\nAdd Relationships for Taxonomy Terms:\n\nUnder Advanced, click Add next to Relationships.\nAdd Parent Term Relationships:\nClick Add again under Relationships and choose Taxonomy term: Parent term.\nSelect the parent relationship for the taxonomy term.\nApply the relationship.\nConfigure the contextual filter:\nWhen the filter value is NOT available: Set this to \"Provide default value\" \u003e Term ID from URL.\n\n### Step 3: Add Fields to Display the Terms and Their Parent Terms\nAdd Fields for Each Level of Terms:\n### Step 4: Configure Display and Path (Optional)\nSet a Path for the View:\nIf you created a page display, set a URL path in Page settings \u003e Path (e.g., /node-terms-hierarchy).\nCustomize the Sorting and Filters (Optional):\nAdd any sorting or filtering options you need. For example, filter by a specific taxonomy vocabulary if your content type uses multiple vocabularies.\n### Step 5: Save and Test the View\nSave your view, and test it by visiting the path you configured.\nThe view should display each node with the associated taxonomy term hierarchy, showing direct terms and all levels of parents.\n\n\n## FIX ISSUES\n\n### Fixing issues releated to `temporary://` and `private://` files\n\u003e Error saving OAuth token file.The specified file 'temporary://filezZvBgU' could not be moved to 'private://.apigee_edge/oauth.dat'.\n\n*Soluation*\n1. Create  `/tmp` folder in path `sites/default/tmp` and update settings.php file `$settings['file_temp_path'] = 'sites/default/tmp';`\n2. Create `/private` folder in path `sites/default/private` and update settings.php file `$settings['file_private_path'] = $app_root . '/sites/default/private';`\n3. Change folders owner on server `sudo chown -R user:group sites/default/private` \u0026 `sudo chown -R user:group sites/default/tmp` \u0026 `sudo chown -R user:group web/sites/default/files` \u0026 `\nchmod -R 775 web/sites/default/files`\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmahmoudsayed96%2Fdrupal-code-snippets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmahmoudsayed96%2Fdrupal-code-snippets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmahmoudsayed96%2Fdrupal-code-snippets/lists"}