Fatal error when enabling Add to Calendar field on Drupal 11: TypeError: Cannot access offset of type Drupal\Core\StringTranslation\TranslatableMarkup
Description
When using the Add to Calendar Field Formatter module on Drupal 11, the site throws a fatal error when attempting to add the “Add to calendar” field to a content type.
Error message:
An AJAX HTTP error occurred.
HTTP Result Code: 500
StatusText: 500 Service unavailable (with message)
TypeError: Cannot access offset of type Drupal\Core\StringTranslation\TranslatableMarkup
in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition()
(core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 45)
Stack trace excerpt:
Drupal\Core\Plugin\DefaultPluginManager->getDefinition()
Drupal\field_ui\Controller\FieldStorageAddController->getFieldSelectionLinks()
This prevents the field from being added via the UI.
Root cause
In add_to_calendar.module, the base field definition uses a manually instantiated TranslatableMarkup object for the label:
$fields['add_to_calendar'] = BaseFieldDefinition::create('add_to_calendar')
->setLabel(new TranslatableMarkup('Add to calendar'))
->setComputed(TRUE)Solution:
Replace new TranslatableMarkup() with the standard translation API call t():
$fields['add_to_calendar'] = BaseFieldDefinition::create('add_to_calendar')
->setLabel(t('Add to calendar'))
->setComputed(TRUE)
->setDisplayConfigurable('view', TRUE)
->setDisplayOptions('view', [
'region' => 'hidden',
])
->setClass(AddToCalendarItemList::class);Edited by drupalbot