Search code examples
javascriptjquerybootstrap-table

Get calling table from column option


I have a few Bootstrap table on one page. Each table has some data attributes (like data-link="test-page" and so on). Besides that, one column of each Bootstrap table uses a column formatter, using data-formatter="actionFormatter". However, I want to get the current table data attributes when actionFormatter is called, so based on the data attributes I can return a string.

Both this and $(this) return an Object, which doesn't work. $(this).closest('table').data() doesn't work either, while I expected that one to be the most true.

Here's the code I use:

<th data-field="actions" data-formatter="actionFormatter" data-events="actionEvents">Actions</th>

this returns a JSON object with the row properties, and $(this).closest('table').data(XXX) return undefined. I expected it to return an array with all the data attributes.

Is there any way to get the current processing table from within the formatter?

Example code:

<!-- table 1 -->
<table
    data-actions="edit,remove"
    data-url="some/url"
>
    <thead>
        <tr>
            <th data-formatter="actionFormatter">Actions</th>
        </tr>
    </thead>
</table>

<!-- table 2 -->
<table
    data-actions="edit,remove"
    data-url="some/url"
>
    <thead>
        <tr>
            <th data-formatter="actionFormatter">Actions</th>
        </tr>
    </thead>
</table>


// actionFormatter:
function actionFormatter(value, row, index, field) {
    // get data-actions from the right table somehow, 
    // and return a string based on data-url/other
    // data attributes
}

Solution

  • It seems that when the action formatter is called, the execution context this is an object with all the bootstrap table row associated data as well as all the data-* attributes of the row.

    Taking that into account you can add an id to each table and a data-table-id attribute to your rows like:

    <table
        id="table-1"
        data-actions="edit,remove"
        data-url="some/url"
    >
    <thead>
        <tr>
            <th data-formatter="actionFormatter" data-table-id="table-1">Actions</th>
        </tr>
    </thead>
    

    so that in your formatter you can retrieve the table DOM Element by using that id:

    function actionFormatter(value, row, index, field) {
        // get data-actions from the right table somehow, 
        // and return a string based on data-url/other
        // data attributes
        var data = $('#' + this.tableId).data();
    }