Tập tành viết Module cho phép tạo image token tùy chỉnh

7th May 2022
Table of contents

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].

>> Tập tành thay đổi dịnh dạng ngày tháng trong Twig

>> Tạo đường dẫn URL với route và tham số trong Twig

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

custom token

Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.