Search code examples
javascripttabulator

Tabulator Modify Image Path


I'm trying to append a path to a cell value inside of Tabulator v3.2 ( http://tabulator.info/docs/3.2 ) that gets pulled from a mySQL table and then display that image represented by the full image path in the Tabulator cell. I have this in the attributes for the .tabulator call:

formatter: function(cell, formatterParams) {
     var celli=cell.getValue();

     if ((celli.indexOf("blankimg") == -1) && (messages["custimgpath"] != "")) {
          var cellf = messages["custimgpath"] + celli + ",\"image\""
     }
     else {
          var cellf = celli
     }
     
     return cellf;
}

As you can see I tried to set the format to 'image' w/in the function. The variables in the if statement do resolve to true. Currently it just enters the full path + formatter in the cell, instead of generating the image tag and putting it in src.

How do I modify it to insert the full path in image tag and also set the formatter to image?


Solution

  • The problem is because you are only returning the string for the path, which is what is displayed.

    In order to show an image you need to return an image element with the path set as its source:

    formatter: function(cell, formatterParams) {
         var celli=cell.getValue();
         var imgEl = document.createElement("img"); //create image element
    
         if ((celli.indexOf("blankimg") == -1) && (messages["custimgpath"] != "")) {
              imgEl.src = messages["custimgpath"] + celli;  //set src of image element
         }
         else {
              imgEl.src = celli; //set src of image element
         }
         
         return imgEl; //return image element
    }
    

    Mutation Alternative

    As an alternative I would suggest using a mutator to update the path value as it come into the table, and then the built in image formatter to display the data.

    In the example below i will aassume that the path is contained on the demo field of the row data

    we start by defining a mutator

    var pathMutator = (value, data, type, mutatorParams, cell){
         if ((value.indexOf("blankimg") == -1) && (messages["custimgpath"] != "")) {
              return messages["custimgpath"] + value
         }
         else {
              return imgEl.src = value;
         }
    }
    

    And then in the column definition for that column we bind the mutator and the formatter

    {title:"Demo Column", field:"demo", formatter:"image", mutator:pathMutator },