Problem/Motivation
I'm using Supported Image Field which extends core's Image field type and would love to use image style tokens with supported image fields. Currently that's not possible because Token module defines those tokens only for core's Image field type.
Note that I did verify that this check $field->getType() == 'image' is the only reason for image style tokens not to work with supported image fields. As a quick experiment, I updated the check to include supported_image field type and image tokens worked just fine.
Steps to reproduce
- Install Supported Image Field module.
- Create and configure field of a type "Supported Image". E.g.
field_supported_image. - Define token that is using supported image field and image style. E.g.
[node:field_supported_image:large]where "large" is the name of an image style. - Confirm that the output of this token is empty.
Proposed resolution
In addition to checking if the field type is image, also check if the field has capability to support image style tokens. Below are some ideas how to do that.
/**
* Implementation of hook_tokens() in Token module.
*/
// Current code: Check only for the field type.
if ($field_item->getFieldDefinition()->getType() == 'image') {}
// Option 1: Implicitly assume if the field extends ImageItem it must be
// compatible. No need for other field types to declare anything.
if (($field_item instanceof \Drupal\image\Plugin\Field\FieldType\ImageItem)) {}
// Option 2: Define empty (marker) interface for this purpose and check if the
// field type implements it.
if ($field_item->getFieldDefinition()->getType() == 'image' || $field_item instanceof ImageFieldCompatible) {}
// Option 3: Check for the boolean attribute defined on the field type.
if ($field_item->getFieldDefinition()->getType() == 'image' || !empty($field_item->getPluginDefinition()['add_image_style_tokens'])) {}
Note: Options 2 and 3 still contain the check for image field type in order to avoid having to modify core's image module.
I like the simplicity of Option 1 but I'm not sure if assumption its making is safe enough.
Making this change would enable any other compatible field type to take advantage of image style tokens. I didn't check if there are any other modules currently that could benefit from this change in addition to Supported Image Field.
Remaining tasks
Decide which approach to take and implement the solution.
User interface changes
None.
API changes
TBD
Data model changes
None.
Issue fork token-3595271
Show commands
Start within a Git clone of the project using the version control instructions.
Or, if you do not have SSH keys set up on git.drupalcode.org:
Comments
Comment #3
vaish commentedI created merge request implementing Option 1 from the issue description. Instead of checking for the field type name, this MR checks if the field inherits from the Image field type. Image style tokens now work with the Image field type and any other field type that extends it.