国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Key Takeaways
The Drupal module
The plugin
The theme
Template
Does it work?
Conclusion
Frequently Asked Questions on Creating Custom Field Formatters in Drupal 8
How do I create a custom field formatter in Drupal 8?
What is the purpose of the @FieldFormatter annotation in Drupal 8?
How can I apply my custom field formatter to a field in Drupal 8?
How can I control the output of my custom field formatter in Drupal 8?
Can I use a custom field formatter for multiple field types in Drupal 8?
How can I create a settings form for my custom field formatter in Drupal 8?
How can I use a custom field formatter to display images in Drupal 8?
Can I create a custom field formatter for a custom field type in Drupal 8?
How can I use a custom field formatter to display links in Drupal 8?
How can I create a custom field formatter for a multi-value field in Drupal 8?
Home Backend Development PHP Tutorial Creating Custom Field Formatters in Drupal 8

Creating Custom Field Formatters in Drupal 8

Feb 18, 2025 am 08:42 AM

Creating Custom Field Formatters in Drupal 8

Key Takeaways

  • Creating a custom field formatter in Drupal 8 involves defining a new formatter class in the src/Plugin/Field/FieldFormatter directory of a custom module, extending from the default ImageFormatter plugin.
  • The new formatter class should override the viewElements() method to return a render array of field data, replacing the default image_formatter theme with a custom one.
  • A new theme, image_title_caption_formatter, is created in the .module file of the module, with the same variables passed as in the default image_formatter theme.
  • The custom field formatter can be applied to a field in Drupal 8 through the “Manage display” tab of the content type, selecting the custom formatter from the “Format” dropdown.
Please be aware that due to the development process Drupal 8 has been undergoing at the time of writing, some parts of the code might be outdated. Take a look at this repository in which I try to update the example code and make it work with the latest Drupal 8 release.

With the introduction of annotated plugins, a lot has changed in Drupal 8. We have a more streamlined approach to describing and discovering pieces of functionality that extend the core. Along with many other components, the former Field API (part of the larger and consolidated Entity API) is now based on plugins.

Creating Custom Field Formatters in Drupal 8

In this tutorial we will go through defining a custom field formatter for an existing field (image). What we want to achieve is to make it possible to display an image with a small caption below it. This caption will be the title value assigned to the image if one exists.

The code we write here can be found in this repository as the image_title_caption module. But let’s see how we can get to that final result.

The Drupal module

Let us start by creating a new custom module (image_title_caption) with only one file:

image_title_caption.info.yml:

name: Image title caption
type: module
description: Uses the image title field as a caption
core: 8.x
dependencies:
  - image

Nothing out of the ordinary here. We can even enable the module already if we want.

The plugin

In Drupal 8, field formatters (like field types and widgets themselves) are plugins. Core ones are defined either by core modules or can be found inside the DrupalCoreFieldPluginFieldFieldFormatter namespace. And like we’ve seen in a previous article in which we looked at custom blocks, plugins go inside the src/Plugin/ folder of our module. In the case of field formatters, this will be src/Plugin/Field/FieldFormatter directory.

Below you can see our own formatter class:

src/Plugin/Field/FieldFormatter/ImageTitleCaption.php:

name: Image title caption
type: module
description: Uses the image title field as a caption
core: 8.x
dependencies:
  - image

This is our plugin. Nothing else to it. Above the class declaration we have the @FieldFormatter annotation through which the plugin gets discovered. We specify a plugin ID (image_title_caption), label and an array of field types this formatter can be used with. In our case, the latter only contains the default image field type but we could support more if we wanted to, even custom field types. The values that go in that array are plugin IDs so if you look at the image field type plugin, you’ll see that its ID is image.

The class looks simple because we are extending from the default ImageFormatter plugin defined by the core Image module. For our purpose, all we need to override is the viewElements() method which is responsible for returning a render array of our field data. The latter can be found inside the $items list and can be used and prepared for rendering.

The first thing we do in this method is make sure we call the parent class method on the items and store that in a variable. That will already prepare the image to be rendered just as if it would normally.

By default, the ImageFormatter plugin (the parent) uses the image_formatter theme inside the render array to output the image field values. What we do here is that for each item, we replace this theme with our own: image_title_caption_formatter. Then we return the elements (render array) just like the parent does.

You’ll notice this a lot in Drupal 8: we get a very good indication on what we need to do from the parent classes we extend. And if you ask me, that is much better than figuring out what some magic hook or function does.

The theme

Since the image_title_caption_formatter theme we specified above is so far imaginary, we’ll need to create it. Inside the .module file of our module we need to implement hook_theme:

image_title_caption.module:

<span><span><?php
</span></span><span>
</span><span><span>/**
</span></span><span><span> * <span>@file
</span></span></span><span><span> * Contains \Drupal\image_title_caption\Plugin\Field\FieldFormatter\ImageTitleCaption.
</span></span><span><span> */
</span></span><span>
</span><span><span>namespace Drupal<span>\image_title_caption\Plugin\Field\FieldFormatter</span>;
</span></span><span>
</span><span><span>use Drupal<span>\Core\Field\FieldItemListInterface</span>;
</span></span><span><span>use Drupal<span>\image\Plugin\Field\FieldFormatter\ImageFormatter</span>;
</span></span><span>
</span><span><span>/**
</span></span><span><span> * Plugin implementation of the 'image_title_caption' formatter.
</span></span><span><span> *
</span></span><span><span> * @FieldFormatter(
</span></span><span><span> *   id = "image_title_caption",
</span></span><span><span> *   label = @Translation("Image with caption from title"),
</span></span><span><span> *   field_types = <span>{
</span></span></span><span><span> *     "image"
</span></span><span><span> *   <span>}
</span></span></span><span><span> * )
</span></span><span><span> */
</span></span><span><span>class ImageTitleCaption extends ImageFormatter {
</span></span><span>
</span><span>  <span>/**
</span></span><span><span>   * <span>{@inheritdoc}
</span></span></span><span><span>   */
</span></span><span>  <span>public function viewElements(FieldItemListInterface $items) {
</span></span><span>    <span>$elements = <span>parent::</span>viewElements($items);
</span></span><span>    <span>foreach ($elements as &$element) {
</span></span><span>      <span>$element['#theme'] = 'image_title_caption_formatter';
</span></span><span>    <span>}
</span></span><span>
</span><span>    <span>return $elements;
</span></span><span>  <span>}
</span></span><span>
</span><span><span>}</span></span>

This should look familiar as it is very similar to Drupal 7. Please take note of the variables we pass to this theme. We intend to override the default image_formatter theme so we should have the same variables passed here as well. Additionally, since the image_formatter theme is preprocessed, we’ll need to create a preprocessor for our theme as well:

<span>/**
</span><span> * Implements hook_theme().
</span><span> */
</span><span>function image_title_caption_theme() {
</span>  <span>return array(
</span>    <span>'image_title_caption_formatter' => array(
</span>      <span>'variables' => array('item' => NULL, 'item_attributes' => NULL, 'url' => NULL, 'image_style' => NULL),
</span>    <span>),
</span>  <span>);
</span><span>}</span>

In this preprocessor we perform two actions:

  • We make sure that the variables passed to the template file will have first been preprocessed by the default image_formatter theme preprocessor. This is so that all the variables are exactly the same and the image gets displayed as it normally would be.
  • We create a new variable called caption that will contain the sanitised value of the image title.

For sanitisation, we use the helper String class statically. We are still inside the .module file so we cannot inject it, but we need to use it at the top of the file:

name: Image title caption
type: module
description: Uses the image title field as a caption
core: 8.x
dependencies:
  - image

Template

Lastly, we need to create a template file for our new theme:

templates/image-title-caption-formatter.html.twig:

<span><span><?php
</span></span><span>
</span><span><span>/**
</span></span><span><span> * <span>@file
</span></span></span><span><span> * Contains \Drupal\image_title_caption\Plugin\Field\FieldFormatter\ImageTitleCaption.
</span></span><span><span> */
</span></span><span>
</span><span><span>namespace Drupal<span>\image_title_caption\Plugin\Field\FieldFormatter</span>;
</span></span><span>
</span><span><span>use Drupal<span>\Core\Field\FieldItemListInterface</span>;
</span></span><span><span>use Drupal<span>\image\Plugin\Field\FieldFormatter\ImageFormatter</span>;
</span></span><span>
</span><span><span>/**
</span></span><span><span> * Plugin implementation of the 'image_title_caption' formatter.
</span></span><span><span> *
</span></span><span><span> * @FieldFormatter(
</span></span><span><span> *   id = "image_title_caption",
</span></span><span><span> *   label = @Translation("Image with caption from title"),
</span></span><span><span> *   field_types = <span>{
</span></span></span><span><span> *     "image"
</span></span><span><span> *   <span>}
</span></span></span><span><span> * )
</span></span><span><span> */
</span></span><span><span>class ImageTitleCaption extends ImageFormatter {
</span></span><span>
</span><span>  <span>/**
</span></span><span><span>   * <span>{@inheritdoc}
</span></span></span><span><span>   */
</span></span><span>  <span>public function viewElements(FieldItemListInterface $items) {
</span></span><span>    <span>$elements = <span>parent::</span>viewElements($items);
</span></span><span>    <span>foreach ($elements as &$element) {
</span></span><span>      <span>$element['#theme'] = 'image_title_caption_formatter';
</span></span><span>    <span>}
</span></span><span>
</span><span>    <span>return $elements;
</span></span><span>  <span>}
</span></span><span>
</span><span><span>}</span></span>

Similar to Drupal 7, the name of this file is important as it mirrors the theme name. As for the contents, they are almost the same as the template used by the image_formatter theme except for the caption printed at the bottom.

Does it work?

Now that we’ve written the code, we need enable the module and clear all the caches if we had made code changes after enabling. It’s time to test it out.

For example, go to the article content type field display settings at admin/structure/types/manage/article/display. For the Image field, under the Format heading, you should be able to select the Image with caption from title format. Save the form and go to admin/structure/types/manage/article/fields/node.article.field_image and make sure the image field title is enabled.

Finally, you can edit an article, upload an image and specify a title. That title will continue to behave as such, but additionally, it will be displayed below the image as a caption. Of course, you can still style it as you wish etc.

Conclusion

In this article we’ve seen how easy it is to create a field formatter and extend default behaviour in Drupal 8. We’ve only touched on overriding the viewElements() of this plugin but we can do much more to further customise things. You are also not required to extend the ImageFormatter. There are plenty of existing plugins you can either extend from or use as an example.

Additionally, you can easily create new field types and widgets as well. It’s a similar process but you’ll need to take some schema information into account, use different annotation classes and write some more code. But the point is you are very flexible in doing so.

Frequently Asked Questions on Creating Custom Field Formatters in Drupal 8

How do I create a custom field formatter in Drupal 8?

Creating a custom field formatter in Drupal 8 involves several steps. First, you need to create a custom module if you don’t have one already. Then, in your custom module, create a new file in the src/Plugin/Field/FieldFormatter directory. The file should be named according to the class it will contain. Inside this file, you will define your custom field formatter class, which should extend the FormatterBase class. You will need to implement several methods, including viewElements() which is responsible for generating the render array for the field values.

What is the purpose of the @FieldFormatter annotation in Drupal 8?

The @FieldFormatter annotation in Drupal 8 is used to define a field formatter. It includes properties like id, label, and field_types. The id is a unique identifier for the formatter, the label is the human-readable name, and field_types is an array of field type machine names that the formatter supports.

How can I apply my custom field formatter to a field in Drupal 8?

To apply your custom field formatter to a field in Drupal 8, you need to go to the “Manage display” tab of the content type, taxonomy term, or other entity type that has the field. Find the field in the list and select your custom formatter from the “Format” dropdown. Then click the “Update” button and save the changes.

How can I control the output of my custom field formatter in Drupal 8?

The output of your custom field formatter in Drupal 8 is controlled by the viewElements() method in your formatter class. This method should return a render array for the field values. You can use Drupal’s theming system to further customize the output.

Can I use a custom field formatter for multiple field types in Drupal 8?

Yes, you can use a custom field formatter for multiple field types in Drupal 8. In the @FieldFormatter annotation of your formatter class, you can specify an array of field type machine names in the field_types property.

How can I create a settings form for my custom field formatter in Drupal 8?

To create a settings form for your custom field formatter in Drupal 8, you need to implement the settingsForm() and settingsSummary() methods in your formatter class. The settingsForm() method should return a form array for the settings, and the settingsSummary() method should return an array of summary lines for the settings.

How can I use a custom field formatter to display images in Drupal 8?

To use a custom field formatter to display images in Drupal 8, your formatter class should extend the ImageFormatterBase class instead of FormatterBase. You will need to implement the viewElements() method to generate a render array for the image field values.

Can I create a custom field formatter for a custom field type in Drupal 8?

Yes, you can create a custom field formatter for a custom field type in Drupal 8. In the @FieldFormatter annotation of your formatter class, you can specify the machine name of your custom field type in the field_types property.

To use a custom field formatter to display links in Drupal 8, your formatter class should extend the LinkFormatter class instead of FormatterBase. You will need to implement the viewElements() method to generate a render array for the link field values.

How can I create a custom field formatter for a multi-value field in Drupal 8?

To create a custom field formatter for a multi-value field in Drupal 8, your formatter class should extend the FormatterBase class and implement the viewElements() method. This method should return a render array for the field values, taking into account that the field may have multiple values.

The above is the detailed content of Creating Custom Field Formatters in Drupal 8. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

See all articles