Add a html field to a form in Drupal 8 & 9

 The Form API changed a bit over the years. This is the way add a html field to a form in Drupal 8 & 9.


$form['filed_name'] = [ '#markup' => '<h2>' . $node->get('field_name')->getString() . '$</h2>', ];


$form['filed_age'] = [ '#markup' => '<h4>' . $node->get('field_age')->getString() . '$</h4>', ];

How to add open graph meta tags programmatically in Drupal 8 & 9

function THEMENAME_page_attachments_alter(array &$page)
{
    $route = \Drupal::routeMatch()->getRouteObject();
    if ($route) {
        $view_id = $route->getDefault('view_id');
        if (!empty($view_id)) {

            if ($view_id == 'devoirs') {
                $img_url = "path/to/image";

                $og_image = array(
                    '#tag' => 'meta',
                    '#attributes' => array(
                        'property' => 'og:image',
                        'content' => $img_url,
                    ),
                );
                $page['#attached']['html_head'][] = [$og_image, 'og_image'];


                $og_description = array(
                    '#tag' => 'meta',
                    '#attributes' => array(
                        "property" => "og:description",
                        "content" => t("Lorem ipsum"),
                    ),
                );
                $page['#attached']['html_head'][] = [$og_description, 'og:description'];

            }
        }
    }
}

Change the user password reset link timeout in Drupal 8 & 9

For Drupal 7: In your settings.php try adding this:

$conf['user_password_reset_timeout'] = '259200';

In Drupal 8, you need to add the following line to your settings.php file:

$config['user.settings']['password_reset_timeout'] = 259200;

One can do the same in Drupal 8 via Drush too.

To get the current setting by default it is 86400 sec means 1 day

drush config:get user.settings password_reset_timeout

To change the reset timeout duration for 2 weeks

drush config:set user.settings password_reset_timeout 1209600 


Example how to change the user password reset link timeout in Drupal 8 & 9.


<?php

/**
 * @file
 * Presents a UI element to set the user password reset link timeout.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Add the password reset link timeout setting on the user settings page.
 *
 * @see \Drupal\user\AccountSettingsForm
 */
function user_pwreset_timeout_form_user_admin_settings_alter(&$form, FormStateInterface $form_state) {
  $config = \Drupal::configFactory()->getEditable('user.settings');

  $form['password_timeout_settings'] = array(
    '#type' => 'details',
    '#title' => t('Password reset timeout'),
    '#open' => TRUE,
    '#weight' => 0,
  );
  $form['password_timeout_settings']['password_reset_timeout'] = [
    '#type' => 'number',
    '#min' => 1,
    '#max' => 31536000,
    '#title' => t('Password Reset Timeout'),
    '#description' => t('Set the timeout in seconds for one-time login links. The default is 86400 seconds (24 hours).'),
    '#default_value' => $config->get('password_reset_timeout', 86400),
  ];
  // Add submit handler to save password_reset_timeout configuration.
  $form['#submit'][] = 'user_pwreset_timeout_user_admin_settings_submit';
}

/**
 * Form submission handler for user_admin_settings().
 *
 * @see user_pwreset_timeout_form_user_admin_settings_alter()
 */
function user_pwreset_timeout_user_admin_settings_submit($form, FormStateInterface $form_state) {
  $timeout_value = $form_state->getValue('password_reset_timeout');
  $config = \Drupal::configFactory()->getEditable('user.settings');
  $config->set('password_reset_timeout', $timeout_value)->save();
}

Clear cache programmatically in Drupal 8

Programmatically using PHP

just use this method where you want to clear the cache:

drupal_flush_all_caches();

there is also other methods to clear caches using:

By Admin UI

Navigate to /admin/config/development/performance and ​click the button "Clear all caches".


By Drush

drush cache-rebuild

//or you can use

drush cr


By update.php

Run update.php (/update.php) is another way of clearing the cache.


By SQL

Delete all data inside  tables that start with "cache_" like this:

TRUNCATE cache_config;

TRUNCATE cache_container;

TRUNCATE cache_data;

TRUNCATE cache_default;

TRUNCATE cache_discovery;

TRUNCATE cache_dynamic_page_cache;

TRUNCATE cache_entity;

TRUNCATE cache_menu;

TRUNCATE cache_render;

TRUNCATE cache_toolbar;


Other Methods:


$variables['#cache']['max-age'] = 0;


\Drupal::service('page_cache_kill_switch')->trigger();


cache_clear_all() // For Drupal-7


drupal_flush_all_caches() // For Drupal-8

PHP

 

If you want to clear specific cache like render cache then you can run the following code:


\Drupal::service('cache.render')->invalidateAll();

PHP

 


If you want to clear specific cache like route cache then you can run the following code:


\Drupal::service("router.builder")->rebuild();

Disable cache for a block in Drupal 8

 use $vars['#cache']['max-age'] = 0 to stop  block being cache in drupal 8.

**

 * Implements hook_preprocess_HOOK()

 */

function mytheme_preprocess_block(&$vars) {

  if($vars['derivative_plugin_id'] == 'block-id-name') {

    $vars['#cache']['max-age'] = 0;

  }

}

for custom Block you can use getCacheMaxAge() method like this

class MyModuleBlock extends BlockBase {

  /**

   * {@inheritdoc}

   */

  public function build() {

  }

  /**

   * @return int

   */

  public function getCacheMaxAge() {

    return 0;

  }

}


Also you can use \Drupal::service('page_cache_kill_switch')->trigger(); to disable the cache for anonymous users and all others too.

function fest_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

     if ($form_id == "node_something_form") {

            //disable the form cache for anonymous users and all others too

\Drupal::service('page_cache_kill_switch')->trigger();

}

}

How i get Taxonomy Term URL Path by tid and TID from Term Name in Drupal 8

For taxonomy term

$aliasManager = \Drupal::service('path_alias.manager');
$alias = $aliasManager->getAliasByPath('/taxonomy/term/'.$tidss);

 

For node 


$aliasManager = \Drupal::service('path_alias.manager');
$alias = $aliasManager->getAliasByPath('/node/'.$id);


Taxonomy term path alias in twig tpl

<a href="{{ path('entity.taxonomy_term.canonical', {'taxonomy_term': node.field_taxonomy_reference.entity.tid.value}) }}">
  <h2>{{ content.field_taxonomy_reference }}</h2>
</a>


To load a single term ID by term name and vocabulary in Drupal 8 you can use the following

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

  ->loadByProperties(['name' => $term_name, 'vid' => 'job_category']);

$term = reset($term);

$term_id = $term->id();


Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...