feat: add Insert module integration for image and file fields#21
Conversation
Implements hook_insert_styles() and hook_insert_render() in modules/insert.inc so custom formatters targeting image, file, or entity_reference fields are exposed as Insert styles. InsertFieldItemList extends EntityReferenceFieldItemList (rather than FieldItemList) so that core formatters such as ImageFormatter, which type-hint against EntityReferenceFieldItemListInterface, work correctly when invoked via the FormatterPreset engine.
|
Warning Review limit reached
More reviews will be available in 30 minutes and 59 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis pull request adds Drupal Insert module integration to Custom Formatters. Custom formatters targeting image, file, and entity_reference fields are now exposed as Insert styles for direct insertion into WYSIWYG editors when the Insert module is installed. The implementation includes two hook functions, a field item list wrapper class, and comprehensive integration tests. ChangesInsert Module Integration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## 4.1.x #21 +/- ##
==========================================
+ Coverage 78.49% 78.54% +0.04%
==========================================
Files 24 25 +1
Lines 1725 1729 +4
Branches 64 64
==========================================
+ Hits 1354 1358 +4
Misses 368 368
Partials 3 3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@composer.json`:
- Line 32: The package description for "drupal/insert" is inconsistent with docs
and implementation: update the composer.json description string so it mentions
that custom formatters target image/file AND entity_reference fields (matching
README and CHANGELOG and the behavior in modules/insert.inc which exposes
entity_reference formatters for the 'file' insert type).
In `@modules/insert.inc`:
- Around line 124-141: Wrap the formatter instantiation and rendering pipeline
in a try/catch that catches Throwable so plugin creation failures and runtime
formatter errors don't bubble to a 500; specifically guard the call to
$plugin_manager->createInstance('custom_formatters:' . $formatter_id, ...) and
subsequent $formatter_instance->viewElements(...) and
\Drupal::service('renderer')->renderInIsolation(...) so that any exception
returns the current fail-closed value '' (and optionally logs the exception via
Drupal::logger or $this->logger->error for diagnostics) while still asserting
the $formatter_instance instanceof FormatterInterface before calling
viewElements.
- Around line 82-90: The code currently defaults $field_type to
'entity_reference' which lets unrelated formatters proceed; instead initialize
$field_type to NULL and only set it when one of the allowed types is found from
$formatter->get('field_types') (the loop that checks
['image','file','entity_reference']). After the loop, if $field_type is still
NULL, reject/skip this formatter path (e.g., return or continue) so it doesn't
fall through into the render path—apply this change around the logic handling
$formatter and ensure behavior aligns with custom_formatters_insert_styles()
compatibility checks.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: c25ca258-02ae-44a7-94dc-056e6c2946b2
📒 Files selected for processing (7)
CHANGELOG.mdREADME.mdcomposer.jsonmodules/insert.incsrc/InsertFieldItemList.phptests/src/Functional/CustomFormattersTestBase.phptests/src/Functional/InsertIntegrationTest.php
- composer.json: mention entity_reference in drupal/insert suggest description - insert.inc: initialise $field_type to NULL and bail early if the formatter does not target an Insert-compatible field type (prevents unintended fallback to entity_reference for non-file formatters) - insert.inc: wrap formatter instantiation and render pipeline in try/catch Throwable so plugin failures and runtime errors return '' instead of a 500 (with logger::error for diagnostics)
Restores Insert module integration from the Drupal 7 version of Custom
Formatters. When the Insert module
is installed, custom formatters targeting
image,file, orentity_referencefields are automatically exposed as Insert styles,allowing formatted output to be inserted directly into WYSIWYG editors.
The integration is purely opt-in — nothing changes when Insert is absent.
Insert hooks
hook_insert_styles()loads all enabled formatters and filters by fieldtype:
imageformatters are exposed for theimageinsert type;fileandentity_referenceformatters for thefileinsert type. Style keys areprefixed
custom_formatters__<id>to avoid collisions.hook_insert_render()builds a temporary field item list from the fileentity passed by Insert, instantiates the matching field formatter plugin,
and returns rendered HTML via
renderInIsolation().Both hooks are implemented in
modules/insert.inc, which is loadedautomatically by the existing
hook_module_implements_alter()mechanismonly when the Insert module is installed.
InsertFieldItemList
A new
InsertFieldItemListclass is introduced to wrap the file entity forrendering. It extends
EntityReferenceFieldItemList(notFieldItemList)for two reasons:
TypedDataInterface, so they cannot be passed as the$parentargumentto
FieldItemList.InsertFieldItemListstores the entity directly andreturns it from
getEntity().ImageFormatterBaseand the
FormatterPresetengine type-hint againstEntityReferenceFieldItemListInterface, whichFieldItemListdoes notsatisfy. Extending
EntityReferenceFieldItemListprovides this withoutany additional implementation.
Changes
modules/insert.inc— new:hook_insert_styles()andhook_insert_render()src/InsertFieldItemList.php— new: field item list wrapper for Insert renderingtests/src/Functional/InsertIntegrationTest.php— new: 5 functional testscovering style filtering, full render hook path, and node-based rendering
for image and entity_reference fields
tests/src/Functional/CustomFormattersTestBase.php— addadminister node form displaypermissioncomposer.json— adddrupal/insert: ^3torequire-dev; add tosuggestREADME.md— document Insert integration in features list; remove from roadmapCHANGELOG.md— add4.1.x-deventryTest plan
DRUPAL_VERSION=11 make lint— CSpell, PHPCS, PHPStan (level 7), Rector,Twig CS Fixer all pass
DRUPAL_VERSION=11 make test— 155 tests / 1,556 assertions passbutton — custom formatters appear in the Insert styles dropdown and render
correctly on insertion
Summary by CodeRabbit
New Features
Documentation
Tests