6

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

3 Answers 3

0

Now (perhaps it was not the case back in the days...) https://www.drupal.org/project/linked_field allows you to link your image directly to the content links fields without using tokens

2

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

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
  • no, that's not the best way of providing link because you will link all wrapping containers that comes with image field including contextual links
    – David
    Commented Feb 20, 2020 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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