Drupal - Adding a link to an image
If you are already building a custom field type, you could add properties for the link to your field:
class MyLinkField extends FieldItemBase {
public static function propertyDefinitions(StorageDefinition $storage) {
...
$properties['title'] = DataDefinition::create('string')
->setLabel(t('Title'));
$properties['url'] = DataDefinition::create('string')
->setLabel(t('URL'));
}
and use it in the field formatter:
class MyLinkFieldFormatter extends FormatterBase {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#type' => 'link',
'#title' => $item->title,
'#url' => Url::fromUri($item->url),
];
}
return $elements;
}