Tos Web Developer provides insights, tutorials, and advice around topics including content strategy, design, Drupal Development, Drupal Custom Module Development, Drupal 8 Custom themes, PHP, Server, Twig, and more

 





This article shows you how to create Token Drupal to return absolute URL and image URL path of article content type content without language prefix.

Follow the instructions below:

Create custom_token.info.yml file: 

 name: Custom Token  
 type: module  
 description: "Example How to create custom token"  
 package: Custom  
 core: 8.x  
 core_version_requirement: ^8 || ^9  
Create custom_token.module file:

The first thing we’ll need in this file is, hook_tokens_info() This is where we’ll define our tokens for Drupal. Which will make your new token available in UI.

In the second half of the code, the hook_tokens() function actually makes the token perform its desired function.

 <?php  
 use Drupal\Core\Render\BubbleableMetadata;  
 use Drupal\image\Entity\ImageStyle;  
 /**  
  * Implements hook_token_info()  
  * @return array  
  */  
 function custom_token_token_info()  
 {  
  $info['tokens']['site']['absolute_url'] = array(  
   'name' => t('Absolute URL'),  
   'description' => t('Url of the site, no language prefix garanted'),  
  );  
  $info['tokens']['site']['custom_image_token'] = array(  
   'name' => t("customimagetoken"),  
   'description' => t("Custom image token.")  
  );  
  return $info;  
 }  
 /**  
  * Implements hook_tokens()  
  * @param $type  
  * @param $tokens  
  * @param array $data  
  * @param array $options  
  * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata  
  * @return array  
  */  
 function custom_token_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)  
 {  
  $replacements = array();  
  global $base_root;  
  foreach ($tokens as $name => $original) {  
   switch ($name) {  
    case 'absolute_url':  
     $replacements[$original] = $base_root;  
     break;  
    case 'custom_image_token':  
     if($node->getType() == 'article'){  
      if(isset($node->get('field_image')->entity)){  
       $image_style = 'large';  
       $style = ImageStyle::load($image_style);  
       $url_final = $style->buildUrl($node->get('field_image')->entity->getFileUri());  
      }  
     }  
     $replacements[$original] = $url_final;  
     break;  
   }  
  }  
  return $replacements;  
 }  


Clear your Drupal 8 caches, and then your new token will be available in UI.



Next steps

Clear your Drupal 8 caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.

Now, go back to your site, and you should be able to see the new custom token.
I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.


No comments:

Post a Comment

| Designed And Blog Post by www.toswebdeveloper.com