Wednesday, 13 December 2023

Datatable Client Side Open & Close Events

 Editor will emit custom DOM events when it performs particular operations, providing the ability to listen for these events and take action on them when they occur, for example starting or completing an edit for a particular row.

open

This event is triggered when the form has been instructed to be displayed for end user input. This is triggered by a call to the open(), bubble() or inline() methods (note that open() can be called automatically by create(), edit() and remove()).
This event is triggered after the display controller is instructed to display the form. As such, the form will typically be available in the document (for addition of events, etc, if required) - it is for the two built in display controllers, although it will still be animating into place.

below is an example. If we want to initialise a field with date picker upon opening the form, we can do that on open event.

  editor.on("open",function(e){

        var cal_settings = {
            enableTime: false,
            dateFormat: js_date_pattern,
            time_24hr:false,
        };

         $(editor.field("field.name")
                        .input()
                    ).flatpickr(cal_settings);
    });

preopen

Before a form is displayed, this event is fired. It allows the open action to be cancelled by returning false from the function.

This event is cancellable by returning false from the event handler, which will block any further action from happening (i.e. actually displaying the form), leaving the form in its existing state.

editor.on("

preOpen

preOpen",function(e){
  alert("Form Pre Opened..");
});


close

This event is triggered when the form has been instructed to close by a call to the close() method (which can occur internally on form submission, background click, close button click, etc, as well as an external call).

Note that the close event is triggered immediately upon the call to close(). As such, if the display controller uses animation to hide the form display (as both of the built in display controllers do) the form DOM elements will still be in the document until the animation is complete - i.e. they will still be present when this method is called. This can be useful for unbinding events that might have been used in the opened form. The display() method should be used to determine whether or not the Editor form is visible or not at any given time.

  editor.on("close",function(e){
  alert("Form Closed..");
});

preClose

Before a form is closed, this event is fired. It allows the close action to be cancelled by returning false from the function. This can be useful for confirming that the user actually wants to close the display (if they have unsaved changes for example).

This event is cancellable by returning false from the event handler, which will block any further action from happening, leaving the form in its existing state.

editor.on("preClose",function(e){
  alert("Form Closed..");
});

closed

This event is triggered when the form has finished closing, taking into account any animation - for example display of a modal for the main form. It can be used to tidy up the document or remove event handlers that were added to the rest of the document.

editor.on("closed",function(e){
  alert("Form Closed Completely..");
});

opened

This event is triggered when the form has finished opening (displaying), taking into account any animation - for example display of a modal for the main form. It can be used to add event handlers or perform any calculations required once the form has fully displayed.

editor.on("opened",function(e){
  alert("Form Opened Completely..");
});

Introduction to Datatables Plugin -Installing & Configuration

 DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, built upon the foundations of progressive enhancement, that adds all of these advanced features to any HTML table. The main features you can see in the image below. You can refer the full features at https://datatables.net/


Installing Datatable

The key part of installing DataTable involves including the DataTable's Javascript and CSS files. The CSS file is optional but provides default styling for your table.

The installation can be performed in several different ways,

  • Using the DataTable's CDN
  • Local Installation by including from local folders
  • Using package manager (NPM)

Using the DataTable's CDN

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css">

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js">
</script>

Local Installation by including from local folders

<link rel="stylesheet" type="text/css" href="/DataTables/datatables.css">

<script type="text/javascript" charset="utf8" src="/DataTables/datatables.js"></script>

Using package manager (NPM)

DataTables and its extensions are available as NPM packages. The package base name is datatables.net, and the extensions and styling integration options are available as individual packages

npm install datatables.net    # Core library  
npm install datatables.net-dt # Styling  

Datatable Initilisation

The table html code be like for eg:-
<div>
    <table width="100%" id="dtExample" class="display " cellspacing="0">
        <thead>
            <tr>
                <th>S.No</th>
                <th>Name</th>
                <th>Age</th>
                <th>City</th>
                <th>State</th>
            </tr>
        </thead>
    </table>
</div>
Here the id provided dtExample will be used for datatable loading and stuffs.
Now you have to add a Js script like:-

$(document).ready( function () {
    $('#dtExample').DataTable();
} )

This will make the basic initilisation of datatable.

DataTables will add ordering, searching, paging, and information to your table by default, allowing your end users to find the information they want as quickly as possible.

If you want to customize your DataTable, this can be done by specifying configuration parameters in an object passed to the DataTable() function.


Configure DataTable

We have in-built options and features in the dataTable plugin to enable/ disable them in our table. 

Some commonly used options/features are,

paging- To enable pagination.
ordering- To enable Sorting.
info- It will display the number of records available on each page.
language- To display custom text rather than the default.
columnDefs- It is nothing but Column Definition. To set properties for each column as we wish.
Scroll X& Y- Set Scroll for width & Height.
Column Rendering- To display not only the text in the td but also we can render any HTML elements like checkbox and dropdownlist in the dataTable.

This we configure in dom property

     $('#dtExample').DataTable({
         dom: 'Bfrtip',
     });


     dom- Bfrtip is B - Buttons, f - filtering input, r - processing display element, t - table, i - informational panel, p - pagination control (if need these controls, then add the alphabet to the dom else remove)

Events 
We have events to catch the datatable changes.

  • Order
  • Search
  • Page


$('#dtExample')
        .on( 'order.dt',  function () { alert( 'Order' ); } )
        .on( 'search.dt', function () { alert( 'Search' ); } )
        .on( 'page.dt',   function () { alert( 'Page' ); } )
.DataTable();


DataSources

DataTables can obtain data from four different fundamental sources:

  • HTML document (DOM)
  • Javascript (array/objects)
  • Ajax sourced data(client-side & server side)
We are going to see how to work with Javascript-sourced data in dataTables


HTML document (DOM)

<table id="dtExample" class="display">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Row 1 Data 1</td>
            <td>Row 1 Data 2</td>
        </tr>
        <tr>
            <td>Row 2 Data 1</td>
            <td>Row 2 Data 2</td>
        </tr>
    </tbody>
</table>

In this method we use table data as normal as we use in other instance. Datatable will use the row data here to process our different requests.

Javascript (array/objects)

Html Code

<table width="100%" id="dtExample" class="display " cellspacing="0">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>City</th>
                <th>State</th>
            </tr>
        </thead>
    </table>

$(document).ready(function () {
     LoadDataTableInstance()
 })
 function LoadDataTableInstance() {
     var dataSource = [
         { name: 'Rohit', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },
         { name: 'Virat', age: 38, city: 'Ooty', state: 'Tamil Nadu' },
         { name: 'Sachin', age: 34, city: 'Erode', state: 'Tamil Nadu' },
         { name: 'Ravindra', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },
         { name: 'Ronaldo', age: 28, city: 'Coimbatore', state: 'Tamil Nadu' },
         { name: 'Messi', age: 38, city: 'Ooty', state: 'Tamil Nadu' },
         { name: 'Maradona', age: 34, city: 'Erode', state: 'Tamil Nadu' },
         { name: 'Pele', age: 34, city: 'Coimbatore', state: 'Tamil Nadu' },
     ]

     dt_table_editor =$('#dtExample').DataTable({
         dom: 'Bfrtip',
         data: dataSource,
         columns: [
             { data: 'name' },
             { data: 'age' },
             { data: 'city' },
             { data: 'state' }
         ],
         buttons: [
            {extend: "create", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-new'},
            {extend: "edit", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-edit'},
            {extend: "remove", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-delete'}
        ],
         "paging": true,
         "info": true,
         "language": {
             "emptyTable": "No data available"
         }
     })
 }

dom: as explained earlier
data- json data
columns- columns should match the table headers, as we mentioned above
buttons- created, edit and delete buttons
paging/ordering/info- to enable those features or not 
language- emptyTable- message to display when data is empty

Ajax sourced data

Here in datasource, the data will be fetched using ajax requests. Rest all will be same.This data can be loaded from client side ajax request or from serverside generated data.

dt_table_editor = $('#dtExample').DataTable({
         dom: 'Bfrtip',
         ajax: {
            url: "/module/controller/action",
            type: "POST"
        },
        serverSide: true,
        columns: [
             { data: 'name' },
             { data: 'age' },
             { data: 'city' },
             { data: 'state' }
         ],
         buttons: [
            {extend: "create", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-new'},
            {extend: "edit", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-edit'},
            {extend: "remove", editor: dt_table_editor,className: 'btn btn-sm btn-primary btn-delete'}
        ],
         "paging": true,
         "info": true,
         "language": {
             "emptyTable": "No data available"
         }
     })

If its from serverside you have to put serverside variable to true.


Some coding parts of working with dataTables


To check whether the DataTable instance is available or not before we proceed with any operations on it,

if($.fn.DataTable.isDataTable('#dtExample')){
   alert('dataTable exist')
}

To read the dataTable & its data,

var dataTable = $('#dtExample').DataTable()
var data = dataTable.rows().data()


To get the particular row values,

var dataTable = $('#dtExample').DataTable()
var dataTableRow = dataTable.row('#' + id).data()

To update a particular row and redraw the DataTable,

var dataTable = $('#dtExample').DataTable()
var dataTableRow = dataTable.row('#' + id).data()
if(dataTableRow){
    dataTableRow['name'] = 'ManiKandan'
    dataTable.row('#' + id).data( dataTableRow ).draw()
}
To destroy a DataTable,

if($.fn.DataTable.isDataTable('#dtExample')){
    $('#dtExample').DataTable().destroy()
}


To remove all the rows,

$('#dtExample').DataTable().rows().remove().draw()

To find the row index,

var dataTable = $('#dtExample').DataTable()
var rowIndex = dataTable.row($(td).closest('tr')).index()