Bootstrap Table Formatter for URL

Leo picture Leo · Jul 4, 2018 · Viewed 8.3k times · Source

Javascript:

function LinkFormatter(value, row, index) {
  return "<a href='"+row.url+"'>"+value+"</a>";
}

HTML:

<th data-field="snum" data-sortable="true" data-formatter="LinkFormatter" >LINK</th>
<th data-sortable="true">DATA</th>

JSON:

{
  data: [
    [
      "https://www.stackoverflow.com",
      "Stackoverflow"
    ]
  ]
}

For this combination I only get an entry in the first column in the table that sais undefined and also links to /undefined. I however just want one column that display Stackoverflow and is a URL to stackoverflow.

What am I missing?

Answer

tad_hey picture tad_hey · Jul 17, 2018

You will have to change your JSON.

It should be something like this:

[ 
  {
    "url": "https://www.stackoverflow.com",
    "nice_name": "Stackoverflow"
  },
  {
    "url": "https://www.facebook.com",
    "nice_name": "Facebook"
  }
];

var data = [{
  "url": "https://www.stackoverflow.com",
  "nice_name": "Stackoverflow"
}, {
  "url": "https://www.facebook.com",
  "nice_name": "Facebook"
}];

function linkFormatter(value, row) {
  return "<a href='" + row.url + "'>" + row.nice_name + "</a>";
}

$(function() {
  $('#table').bootstrapTable({
    data: data
  });
});
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css">

<table data-toggle="#table" id="table">
  <thead>
    <tr>
      <th data-field="url" data-formatter="linkFormatter" data-sortable="true">Link</th>
    </tr>
  </thead>
</table>

Example on bootstrap-table site where same JSON format is required when initializing table through data fields. Example:

<table id="table"
       data-toggle="table"
       data-height="460"
       data-url="../json/data1.json">
  <thead>

Bootstrap documentation & examples