3

Is there a module or a way in core to have an Image field be a clickable link to a URL that is either entered as an additional setting for the Image field or can be pulled from another field that stores that URL.

This https://www.drupal.org/project/linked_field looks like what I want, but there doesn't seem to be a token that I can use that will do what I want.

This also looks exactly like I want but it's for D7. https://www.drupal.org/project/linkimagefield

I'm using this for a Custom Field Type

1

You could create a template file for your content type.

node--[type-name].html.twig

<a href="{{ content.field_url }}"> {{ content.field_image }} </a>

1

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;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.