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()


Monday 16 May 2022

Building Docker Container with PHP 7.3 and Mariadb

    Docker- Definition

Docker provides the ability to package and run an application in a loosely isolated environment called a container. The isolation and security allows you to run many containers simultaneously on a given host. Containers are lightweight and contain everything needed to run the application, so you do not need to rely on what is currently installed on the host. You can easily share containers while you work, and be sure that everyone you share with gets the same container that works in the same way.

Docker Advantages

You will be having projects developed in different PHP versions. Sometimes some of applications you dint want to upgrade but still you need to run on your local. What you will do? suppose you have  projects in php version 5.3. 5.6 and 7.3, 8 , running this simultaneously  in your local server or machine wont be possible as the wamp or xamp wont support it. So if you are running latest version of Wamp and you try to run projects in 5.6, it wont work. This is one of the many use cases of a Docker. You can google it for other advantages.

In this article , I will be giving instructions on how to build a container in PHP 5.3 and Mysql.

First Step is to Install Docker in your computer

Folder Structure




In Our Main Folder , first we have to create a file called docker-compose.yml

in this file we have to define the commands. Commands in the sense, the Docker image to use for PHP and MySQL. means all the configurations which  is needed for the site to work. By adjusting this file, we create containers for each versions. So For latest PHP version copy this code into the file.

version: '3.8'

services:

    php-apache-environment:

        container_name: php-apache5

        build:

            context: ./php

            dockerfile: Dockerfile

        depends_on:

            - db5

        volumes:

            - ./php/src:/var/www/html/

        ports:

            - 8005:80

    db5:

        container_name: db5

        image: mariadb:10.4

        restart: always

        environment:

            MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD

            MYSQL_DATABASE: MYSQL_DATABASE

            MYSQL_USER: MYSQL_USER

            MYSQL_PASSWORD: MYSQL_PASSWORD

        ports:

            - "9905:3306"

    phpmyadmin:

        image: phpmyadmin/phpmyadmin

        ports:

             - '8085:80'

        restart: always

        environment:

            PMA_HOST: db5

            UPLOAD_LIMIT: 300M

        depends_on:

                  - db5  

 Here you can see its mentioning the php latest Image.then in the context defining the folder to search for file Docker file. Then you can see it maps the port 8005 for 80. This is because normally the apache opens port 80 for web service. so here it points to 8005. so localhost:8005 will be assigned to this project. Next is it defines the mysql image and naming as a container. Also its providing the username and password for mysql to create. Here also you can see the port 3306 is mapped to 9905. For accessing phpmyadmin, it maps port 80 to 8085. Then in environment we can set the resource limits. Here am setting the upload limit to 200 MB.

Now next step is to create the file Dockerfile inside the php folder as defined in the context attribute.


Use image Mariddb:10.4


In the Dockerfile Put contents like this:-

FROM php:7.3-apache

RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli

RUN apt-get update && apt-get upgrade -y

RUN a2enmod rewrite


Here You can see its asking for the php:7.3 version image. Then enabling the mysqli extension. Iam also enabling the rewrite access so that .htaccess will be working for our project.


Now next step is to put our working files inside the php/src/ folder , so that the scripts starts executing. This path is defined in docker-composer.yml. Its mapping the var/www/html to our specified directory.


Now for testing purpose we can put php info printing code inside the index.php file. So we can check which version of PHP installed in the project.

So our Project scripting is over. lets see how this will work..

Now You have to open the command prompt or terminal and navigate to the project folder.

type docker-compose up command


If its first time, it will create the container for you. It will take some seconds to install all the things.

If you want to rebuild the entire container if you changed some version numbers in the config files.

Then you can use the command docker-compose up --build . This will rebuild the container and will

 start working. Now if you access the url http://localhost:8004 as mentioned in the docker-compose.yml

 file. you can access the site.








So accessing http://localhost:8005, you will get:-








You can see the Php version is 8.0. Here you can put your project files and run using the url.

Now to access PHPmyadmin, go to url: http://localhost:8085








You can login using username:root, password: MYSQL_ROOT_PASSWORD. After login you can see the phpmyadmin dashboard just like default.





You can create database of your wish and import it. Connect it and it will start working. In MYSQL connect settings, you can create your own user and give permission to access the database if you want.

You can create a new db user by following this:-

Click on User accounts Menu


Scroll down list of users, you can see link to create new user


In top of page, give username and a strong password.


Set all the permission.  and create user.


Now when you are defining the connection settings to the site in the host name filed you have to put the db instance name which we defined in docker-composer.yml file and same you can see at hostname of phpmyadmin also.















Now your environment will be ready. You can see your container running in docker dashboard.


Now try this and of you have any queries comment below.

You can access Github code here:- https://github.com/litto/docker-php-73-mariadb