dvn22
dvn22

Reputation: 151

CakePHP 3.6.14: Bootstrap table is sorting by html not text

I am using bootstrap table with cakephp. The content of each cell is a link, so in order to display the text and not the html code I am using data-escape="false" in the <table> tag.

But now when I try to sort, sorting is not working as expected because it sorts the rows based on the html code of the link and not the text displayed.

This is my table:

<table class="table responsive" id="table" data-toggle="table"
    data-search="true"
    data-filter-control="true" 
    data-show-export="true"
    data-click-to-select="true"
    data-toolbar="#toolbar"
    data-escape="false">
    <thead>
        <tr>
              <th data-field="name" data-filter-control="input" data-sortable="true" scope="col"><?= __('Title') ?></th>
        </tr>
    </thead>
    <tbody>
       <?php foreach ($tasks as $task):?>
           <tr>
              <td><?= $task->has('name') ? $this->Html->link($task->name, ['controller' => 'Tasks', 'action' => 'edit', $task->id]) : '' ?></td>
           </tr>
       <?php endforeach; ?>
   </tbody>
</table>

Upvotes: 0

Views: 398

Answers (1)

PHPnoob
PHPnoob

Reputation: 614

You can use your own javascript sorter with "data-sorter" attribute.

<th data-field="name" data-filter-control="input" data-sortable="true" data-sorter="linksSorter" scope="col"><?= __('Title') ?></th>

Then for example :

function linksSorter(a, b) {
    var a = $(a).text();
    var b = $(b).text();
    if (a < b) return -1;
    if (a > b) return 1;

    return 0;
}

Upvotes: 4

Related Questions