Skip to main content
Drupal: Mapping fields
Gregory Claeyssens avatar
Written by Gregory Claeyssens
Updated over 6 months ago

As of Drupal 8 and up, our module uses the Drupal Plugin API to make it extendable. This means you can now configure and alter the way each field is mapped in a more structured and flexible way.

Also, check out our developer documentation to find out more about webhook publishing in general.


Introduction

The logic for field mapping is provided by so-called plugins (annotated classes in a specific namespace), the annotation providing the administrative label. The defining module does not matter, the plugin id must be unique across all modules.

Examples

Defining a simple field mapping

To define a field mapping, place a MyStoryChiefFieldHandler.php plugin class file in the following directory structure:
​my_module/src/Plugin/StoryChiefFieldHandler
(See the explanation of the PSR-4 standard for more information.) This plugin class will be automatically discovered and loaded when my_module is enabled.

<?php

namespace Drupal\custom_storychief_mapping\Plugin\StoryChiefFieldHandler;

use Drupal\storychief\Plugin\FieldHandlerType\BaseFieldHandlerType;

/**
* Class ContentStoryChiefFieldHandler.
*
* @StoryChiefFieldHandler(
* id = "excerpt",
* label = @Translation("Custom mapping of the excerpt"),
* drupal_field_name = "field_intro",
* )
*/
class IntroStoryChiefFieldHandler extends BaseFieldHandlerType {
}

In this example, the StoryChief excerpt will be mapped to the field_intro in Drupal.

Annotation explained:

  • id: Plugin ID (unique). Will also try to find the correct data inside the Webhook Payload.

  • drupal_field_name: Optional, will try and map the data on this Drupal field.

Provided Field Handler Types

The StoryChief module ships with a number of predefined field handlers (see Drupal\storychief\Plugin\FieldHandlerType namespace).

BaseFieldHandlerType.php

The base for all other FieldHandlerTypes, provides basic functionality for getting the payload value and setting the Drupal field.

EntityReferenceFieldHandlerType.php

Handles saving to ID's Entity Reference fields.

ImageFieldHandlerType.php

Handles saving to Image fields. The incoming data (URL) gets sideloaded into Drupal's media library.

ParagraphFieldHandlerType.php

Handles saving to Paragraph fields (see the Paragraphs project). By default, this class will save all content into a single paragraph type.

TaxonomyTermFieldHandlerType.php

Extends the EntityReference field and adds a lookup on incoming value to fetch the appropriate IDs.

MetatagFieldHandlerType.php

Handles saving seo fields to the appropriate fields provided by the Metatag project.

Resources


πŸ“š Next steps

Did this answer your question?