Tập tành tạo một custom field formatter trong Drupal 9

7th May 2022
Table of contents

Trong Drupal, các giá trị field được hiển thị cho người dùng cuối thông qua field formatter.

Các định dạng (formatter) đi kèm với các trường mặc định trong Drupal thường khá cơ bản. Nếu bạn muốn thay đổi hiển thị của một trường, thì cách tốt nhất để làm điều này là viết một định dạng tùy chỉnh (custom formatter).

Trong hướng dẫn này, chúng tôi sẽ tạo một định dạng tùy chỉnh cho trường liên kết (Link) hiển thị video YouTube (embeded Youtube Video). Trường này sẽ lưu link của Youtube và sau đó được hiển thị cho người dùng trên web dưới Iframe.

Bước 1 - Tạo module YouTube Formatter

Tạo module YouTube Formatter (youtube_format) trong thư mục modules/, bước đầu tiên tạo file .info.yml

name: YouTube Formatter
type: module
description: 'YouTube formatter'
core: 8.x
core_version_requirement: ^8 || ^9
package: Custom
dependencies:
  - field

Bước 2 - Tạo Formatter Class

Tạo một class YouTubeLinkFormatter  extends từ class FormatterBase, sau đó sử dụng viewElements() để hiển thị formatter.

Tạo file  <module>/lib/Drupal/youtube_formatter/Plugin/Field/FieldFormatter/YouTubeLinkFormatter.php với nội dung sau: 

<?php

namespace Drupal\youtube_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

/**
 * Plugin implementation of the 'youtube_link' formatter.
 *
 * @FieldFormatter(
 *   id = "youtube_link",
 *   label = @Translation("YouTube Formatter"),
 *   field_types = {
 *     "link"
 *   }
 * )
 */
class YouTubeLinkFormatter extends FormatterBase
{

    /**
     * Builds a renderable array for a field value.
     *
     * @param \Drupal\Core\Field\FieldItemListInterface $items
     *   The field values to be rendered.
     * @param string $langcode
     *   The language that should be used to render the field.
     *
     * @return array
     *   A renderable array for $items, as an array of child elements keyed by
     *   consecutive numeric indexes starting from 0.
     */
    public function viewElements(FieldItemListInterface $items, $langcode)
    {
        $elements = array();

        foreach ($items as $delta => $item) {
            $url =$item->getUrl();
            $elements[$delta] = array(
                '#theme' => 'youtube_link_formatter',
                '#url' => $url,
            );
        }

        return $elements;
    }
}

Chú ý: field_types là thông số quan trọng, nếu không thêm vào "link" thì custom formatter  của bạn sẽ không được xuất hiện trong trình quản lý.

Bước 3 - Tạo template

Thay vì viết html code vào trong viewElements,  chúng ta sẽ sử dụng custom template. Trong trường hợp này nó là youtube_link_formatter 

1. Tạo file youtube_formatter.module và thêm đoạn code dưới :

<?php
/**
* @file
* Defines simple YouTube formatter for the link field.
*/

/**
 * Implements hook_theme().
 */
function youtube_formatter_theme() {
    return array(
        'youtube_link_formatter' => array(
            'variables' => array('url' => NULL),
            'template' => 'youtube-link-formatter',
        ),
    );
}

2. Tạo template tên youtube-link-formatter.html.twig có nội dung:

<iframe width="100%" height="400"
        src="{{ url }}"
        frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Bây giờ bạn chỉ cần cài đặt module YouTube Formatter và Link , sau đó tạo một bài viết và thêm link youtube vào thử

Tạo một custom field formatter

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ì đã.