Skip to main content

[Thủ Thuật Drupal] Drupal 8,9 - Tạo image token tùy chỉnh

Token là một yếu tố cơ bản trong bất kỳ trang web Drupal nào. Nó bao gồm các phần văn bản tùy chỉnh có thể được sử dụng làm trình giữ chỗ cho các giá trị được xác định trước. Các mã thông báo này được đặt ở định dạng [token:type].

Trong bài viết này, tôi sẽ hướng dẫn bạn cách tạo  image token tùy chỉnh trong Drupal 8/ Drupal 9.

Thực hiện theo các hướng dẫn bên dưới để tạo module  "custom_image_token" :

Tạo file custom_image_token.info.yml

name: Custom image token
type: module
description: "Return url of image in custom token"
package: Custom
core: 8.x
core_version_requirement: ^8 || ^9

Tạo file custom_image_token.module

Điều đầu tiên chúng ta sử dụng hook_tokens_info () để khai báo token cho Drupal sau đó token mới sẽ được xuất hiện trong UI( giao diện người dùng).

Trong phần thứ hai của code, hàm hook_tokens () được sử dụng để thực sự thực hiện chức năng mong muốn của nó.

<?php
use Drupal\image\Entity\ImageStyle;

/**
 * Implements hook_token_info()
 * @return array
 */
function custom_image_token_token_info() {
  $type = array(
    'name' => t('Custom'),
    'description' => t('Custom Tokens'),
  );

  $node['custom_image_token'] = array(
    'name' => t("customimagetoken"),
    'description' => t("Custom image token.")
  );

  return array(
    'types' => array('customtoken' => $type),
    'tokens' => array('customtoken' => $node)
  );
}

/**
 * Implements hook_tokens()
 * @param $type
 * @param $tokens
 * @param array $data
 * @param array $options
 * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
 * @return array
 */
function custom_image_token_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $url_final = '';
  $replacements = array();
  if ($type == 'customtoken' && !empty($data['node'])) {
    $node = $data['node'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        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;
}

Xóa Cache và kiểm tra

Image
Tạo custom Image Token trong Drupal 8,9

Source Code