Saturday, January 15, 2022

[FIXED] CakePHP 3.6.14: Bootstrap table is sorting by html not text

Issue

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>

Solution

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


Answered By - PHPnoob

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.