how to implement a field formatter for text fields that outputs the an image

by arpitk   Last Updated July 11, 2019 13:07 PM

Hi I want to add a text field for-matter where if i write the link of an image into the text field then it should show me image as a value when displaying the node. how can i achieve this with coding please help me. Thank you

Tags : hooks

Answers 2

Use a view to display this content type. Then set the view to display fields.

You can then add the text field and then add a template for this specific field.

You can technically override the output of the field and put the html there, but it's bad practice to put html into the database. So I would stick with doing it with a view template file. Then you can also put in an alt tag from the title field or wherever. The only issue is you won't have the image height/width which is best practice to include, you could use some fancy javascript to do this but it may not be worth the cost. documentation on views template naming:

July 11, 2019 19:07 PM

You can follow the example on creating a custom Field Formatter. Inside the viewElements function, you can add an if statement to check if the remote file exist. If it does, assign the url to the markup. If not, assign some text:

viewElements(FieldItemListInterface $items, $langcode) {
    $element = [];

    foreach ($items as $delta => $item) {
        $file = $item->value;
        $file_headers = @get_headers($file);
        if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
            $url = Url::fromUserInput($file);
            $markup = "<img src={$url->toUriString()} \>";
        else {
            $markup= "File Not Found";
      // Render each element as markup.
      $element[$delta] = ['#markup' => $markup];

    return $element;

Part of this answer is from stackoverflow.
I have not tested this, but it should be close.

Kevin Nowaczyk
Kevin Nowaczyk
July 11, 2019 19:31 PM

Related Questions

Updated April 03, 2015 21:20 PM

Updated April 22, 2015 20:03 PM

Updated April 06, 2015 19:03 PM

Updated April 13, 2015 20:03 PM