Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By geraldito on
Great news that Drupal 8 WYSIWYG editor now is ready for image captions, but actually I need image captions showing with images configured by Manage Display of content type.
The problem is that none of the modules like Image Caption are not D8 ready by now.
The right way to implement this seems to be by creating a custom Field Formatter. Actually there is a fantastic article showing how to implement this as a module. But something changed in Drupal API and using this code shows a blank Manage Display page without any error reporting.
Anybody has a solution for adding image captions to Drupal 8?
Comments
working!
Using module from the repo linked to from https://www.sitepoint.com/community/t/creating-custom-field-formatters-i...
Wasn't working initially but by changing line 29 of imagecaption.php from
public function viewElements(FieldItemListInterface $items) {
to
public function viewElements(FieldItemListInterface $items, $langcode) {
I could install the module OK and select the formatter, and the new formatter was used, but the caption was not showing up.
Then changed line 21 of image_caption_title.module from
$vars['caption'] = SafeMarkup::checkPlain($vars['item']->get('title')->getValue());
to
$vars['caption'] = SafeMarkup::checkPlain($vars['item']->get('alt')->getValue());
and captions now show :)
error when installing
Fatal error: Cannot use Drupal\Component\Utility\String as String because 'String' is a special class name
String is reserved in PHP 7 so now there is a new class
https://www.drupal.org/node/2481955
A simple solution using twig
Great solution
This is a simple solution that works well.
To use this, enable the TITLE field on your Image field and paste the above code file into your theme as /themes/your_theme/templates/field/image-formatter.html.twig.
Image Caption has a working D8 version
We now have a working D8 version of Image Caption here: https://www.drupal.org/sandbox/maskys/2933889
This is still in development and should not be used in prod.
How do we enable the image
How do we enable the image caption on WYSIWYG editor on D8?
I'm using the TWIG template that hihagen posted here.