DataTables how to fill a column with a hyperlink?

3.6k Views Asked by At

I am using DataTables server-side processing and would like to add a hyperlink in the first cell of some of the tables.

I am able to add a column and have the table render correctly, but I can't figure out how to get a hyperlink into the cell.

I don't want this in every table, right now it's just going to be for two of them, but that is subject to change.

I use the same initialization for all of my tables, but all the tables do not have the same columns. There could be anywhere from 3 to 65 columns depending on what table I'm rendering so I can't just add the columns into the initialization. Here is how I'm initializing right now:

$(document).ready(function ()
{
    // Setup - add a text input to each footer cell
    $('#DataTable tfoot th').each(function ()
    {
        var title = $(this).text();
        $(this).html('<input type="text" placeholder="Search ' + title + '" />');
    });

    var table = $('#DataTable').DataTable({
        "lengthMenu": [[25, 50, 75, 100, 150, -1], [25, 50, 75, 100, 150, 'All']],
        "dom": '<"top"Bifpl<"clear">>rt<"bottom"ip<"clear">>',
        "buttons": [{
            extend: 'collection',
            text: 'Selection',
            buttons: ['selectAll', 'selectNone']
        }, {
            extend: 'collection',
            text: 'Export',
            buttons: ['export', 'excel', 'csv', 'pdf', { extend: 'excel',
                text: 'Export Current Page',
                exportOptions: {
                    modifier: {
                        page: 'current'
                    }
                },
                customize: function (xlsx)
                {
                    var sheet = xlsx.xl.worksheets['sheet1.xml'];
                    $('row:first c', sheet).attr('s', '7');
                }
            },

            {
                text: 'Export All to Excel',
                action: function (e, dt, button, config)
                {
                    dt.one('preXhr', function (e, s, data)
                    {
                        data.length = -1;
                    }).one('draw', function (e, settings, json, xhr)
                    {
                        var excelButtonConfig = $.fn.DataTable.ext.buttons.excelHtml5;
                        var addOptions = { exportOptions: { 'columns': ':all'} };

                        $.extend(true, excelButtonConfig, addOptions);
                        excelButtonConfig.action(e, dt, button, excelButtonConfig);
                    }).draw();
                }
            }]
        }
        ],
        "fixedHeader": {
            header: true,
            footer: true
        },
        "select": true,
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "./ServerSide.php",
            "type": "POST"
        },
//Added this to the initialization
        columnDefs: [
        {
            targets: 0,
            render: function (data, type, row, meta)
            {
                if (type === 'display')
                {
                    data = '<a href="FormToEdit.php?everything=' + encodeURIComponent(row) + '">' + data + '</a>';
                }
                return data;
            }
        }],
//It adds the hyperlink to all tables and not just the ones that I want
        initComplete: function ()
        {
            var api = this.api();

            // Apply the search
            api.columns().every(function ()
            {
                var that = this;

                $('input', this.footer()).on('keyup change', function ()
                {
                    if (that.search() !== this.value)
                    {
                        that
                          .search(this.value)
                          .draw();
                    }
                });
            });
        }
    });
});

Here's how I create the tables:

<?php
    $hsql = "select Headings from TableHeadings where TableName = '$TableName' order by Id";

    $getHeadings = $conn->query($hsql);
    $rHeadings = $getHeadings->fetchALL(PDO::FETCH_ASSOC);
    $CountHeadings = count($rHeadings);
    $tsqlHeadings = '';
    for ($row = 0; $row < $CountHeadings; $row++)
    {
        $headings[$row] = $rHeadings[$row]["Headings"];
    }
?>
<table id="DataTable" class="display nowrap" style="width: 100%; border: 1px">
    <thead>
        <tr>
            <?php
            foreach($headings as $heading)
            {?>
            <th class="cell"><?php echo $heading; ?></th><?php
            }?>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <?php
            foreach($headings as $heading)
            {?>
            <th class="cell"><?php echo $heading; ?></th><?php
            }?>
        </tr>
    </tfoot>
</table>

EDIT

I have edited the initialization script above with what I've added. The problem now is that it adds this hyperlink to all tables and not just to the ones that have the Edit column. How would I modify this further to get it only on the table if the first column header is Edit?

1

There are 1 best solutions below

2
On BEST ANSWER

I have decided to go about this in a different way.

The tables that will be editable will be given a different ID and then initialized with the above code. The rest will be initialized without the part that creates the hyperlink in the first column. so now I have this for creating my tables:

<table id="<?php if($Edit == 1){echo "DataTableEdit";}elseif($Edit == 0){echo "DataTable";}?>" class="display nowrap" style="width: 100%; border: 1px">

So that if they have $Edit = 1 they will get a different initialization. The new scripts now look like this:

<script type="text/javascript" class="init">
    $.fn.dataTable.ext.buttons.export =
    {
        className: 'buttons-alert',
        "text": "Export All Test",
        action: function (e, dt, node, config)
        {
            alert('Export All Test');
        }
    };

    $(document).ready(function ()
    {
        // Setup - add a text input to each footer cell
        $('#DataTableEdit tfoot th').each(function ()
        {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        });

        var table = $('#DataTableEdit').DataTable({
            "lengthMenu": [[25, 50, 75, 100, 150, -1], [25, 50, 75, 100, 150, 'All']],
            "dom": '<"top"Bifpl<"clear">>rt<"bottom"ip<"clear">>',
            "buttons": [{
                extend: 'collection',
                text: 'Selection',
                buttons: ['selectAll', 'selectNone']
            }, {
                extend: 'collection',
                text: 'Export',
                buttons: ['export', 'excel', 'csv', 'pdf', { extend: 'excel',
                    text: 'Export Current Page',
                    exportOptions: {
                        modifier: {
                            page: 'current'
                        }
                    },
                    customize: function (xlsx)
                    {
                        var sheet = xlsx.xl.worksheets['sheet1.xml'];
                        $('row:first c', sheet).attr('s', '7');
                    }
                },

                {
                    text: 'Export All to Excel',
                    action: function (e, dt, button, config)
                    {
                        dt.one('preXhr', function (e, s, data)
                        {
                            data.length = -1;
                        }).one('draw', function (e, settings, json, xhr)
                        {
                            var excelButtonConfig = $.fn.DataTable.ext.buttons.excelHtml5;
                            var addOptions = { exportOptions: { 'columns': ':all'} };

                            $.extend(true, excelButtonConfig, addOptions);
                            excelButtonConfig.action(e, dt, button, excelButtonConfig);
                        }).draw();
                    }
                }]
            }
            ],
            "fixedHeader": {
                header: true,
                footer: true
            },
            "select": true,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "./ServerSide.php",
                "type": "POST"
            },
            columnDefs: [
            {
                targets: 0,
                render: function (data, type, row, meta)
                {
                    if (type === 'display')
                    {
                        data = '<a href="FormToEdit.php?everything=\'' + encodeURIComponent(row) + '\'">' + data + '</a>';
                    }
                    return data;
                }
            }],
            initComplete: function ()
            {
                var api = this.api();

                // Apply the search
                api.columns().every(function ()
                {
                    var that = this;

                    $('input', this.footer()).on('keyup change', function ()
                    {
                        if (that.search() !== this.value)
                        {
                            that
                              .search(this.value)
                              .draw();
                        }
                    });
                });
            }
        });
    });
</script>
<script type="text/javascript" class="init">
    $.fn.dataTable.ext.buttons.export =
    {
        className: 'buttons-alert',
        "text": "Export All Test",
        action: function (e, dt, node, config)
        {
            alert('Export All Test');
        }
    };

    $(document).ready(function ()
    {
        // Setup - add a text input to each footer cell
        $('#DataTable tfoot th').each(function ()
        {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');
        });

        var table = $('#DataTable').DataTable({
            "lengthMenu": [[25, 50, 75, 100, 150, -1], [25, 50, 75, 100, 150, 'All']],
            "dom": '<"top"Bifpl<"clear">>rt<"bottom"ip<"clear">>',
            "buttons": [{
                extend: 'collection',
                text: 'Selection',
                buttons: ['selectAll', 'selectNone']
            }, {
                extend: 'collection',
                text: 'Export',
                buttons: ['export', 'excel', 'csv', 'pdf', { extend: 'excel',
                    text: 'Export Current Page',
                    exportOptions: {
                        modifier: {
                            page: 'current'
                        }
                    },
                    customize: function (xlsx)
                    {
                        var sheet = xlsx.xl.worksheets['sheet1.xml'];
                        $('row:first c', sheet).attr('s', '7');
                    }
                },

                {
                    text: 'Export All to Excel',
                    action: function (e, dt, button, config)
                    {
                        dt.one('preXhr', function (e, s, data)
                        {
                            data.length = -1;
                        }).one('draw', function (e, settings, json, xhr)
                        {
                            var excelButtonConfig = $.fn.DataTable.ext.buttons.excelHtml5;
                            var addOptions = { exportOptions: { 'columns': ':all'} };

                            $.extend(true, excelButtonConfig, addOptions);
                            excelButtonConfig.action(e, dt, button, excelButtonConfig);
                        }).draw();
                    }
                }]
            }
            ],
            "fixedHeader": {
                header: true,
                footer: true
            },
            "select": true,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "./ServerSide.php",
                "type": "POST"
            },
            initComplete: function ()
            {
                var api = this.api();

                // Apply the search
                api.columns().every(function ()
                {
                    var that = this;

                    $('input', this.footer()).on('keyup change', function ()
                    {
                        if (that.search() !== this.value)
                        {
                            that
                              .search(this.value)
                              .draw();
                        }
                    });
                });
            }
        });
    });
</script>

This is allowing me to have table that are editable and tables that are not. and I can just add the $Edit to whatever table needs to be edited.