Articles in this section
Category / Section

How to render EJ2 Gantt using PHP and update DB on CRUD operations

3 mins read

This article explains you the steps required to render Essential JS 2 Gantt chart and perform CRUD operation using PHP. The following are the steps required to render Gantt sample.

 

Initializing EJ2 Gantt Control

Step 1: Using CDN link, can refer script and style in the PHP file.

<head>
      <!--Syncfusion Essential JS 2 styles-->
      <link rel="stylesheet" href="https://cdn.syncfusion.com/ej2 /material.css" />
 
      <!--Syncfusion Essential JS 2 scripts -->
      <script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js"></script>
</head>

Step 2: Add Gantt control to application.

<body>
    <div id=”Gantt”></div>
</body>

Step 3: Add corresponding scripts to script tag.

<script type="text/javascript">
var gantt = new ej.gantt.Gantt({
taskFields: {
id: 'taskID',
name: 'taskName',
startDate: 'startDate',
endDate: 'EndDate',
duration: 'duration',
parentID: 'parentID'
},
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
allowTaskbarEditing: true,
showDeleteConfirmDialog: true
},
toolbar: ['Add', 'Edit', 'Update', 'Delete', 'Cancel', 'ExpandAll', 'CollapseAll'],
enableContextMenu: true,
});
gantt.appendTo('#Gantt');
</script>

Step 4: Data Binding

Using getData() method, the JSON data will be fetched from the server. Find the following code snippet to bind the data source using the dataManager.

<script type="text/javascript">
var gantt = new ej.gantt.Gantt({
dataSource: new ej.data.DataManager({
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=getData', crossDomain: true
}).executeQuery(new ej.data.Query()).then(function (e) {
gantt.dataSource = e.result;
}),
taskFields: {
id: 'taskID',
name: 'taskName',
startDate: 'startDate',
endDate: 'EndDate',
duration: 'duration',
parentID: 'parentID'
},
editSettings: {
allowAdding: true,
allowEditing: true,
allowDeleting: true,
allowTaskbarEditing: true,
showDeleteConfirmDialog: true
},
toolbar: ['Add', 'Edit', 'Update', 'Delete', 'Cancel', 'ExpandAll', 'CollapseAll'],
enableContextMenu: true,
});
gantt.appendTo('#Gantt');
</script>

In server-side, the data from database can be retrieved by using the getData() method.

function getData(){
//connection to the database
$dbhandle = mysqli_connect("localhost", "root","", "gantt");
$selected = mysqli_select_db($dbhandle,"gantt");
//execute the SQL query and return records
$result = mysqli_query($dbhandle, "SELECT taskID, taskName,startDate, endDate,duration,parentID FROM gantt");
//fetch the data from the database
$emparray=array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[]=$row;
}
echo json_encode($emparray);
}
if(function_exists($_GET['action'])) {
$_GET['action']();
}

 

CRUD Operations

1.Add

actionComplete client side event gets triggered while adding new task data. Using this event, we can insert new task data into the database.

The code snippet to add new task item to database.

<script type="text/javascript">
var gantt = new ej.gantt.Gantt({
actionComplete: function (args) {
if (args.action == "add" && args.newTaskData) {
var data = JSON.stringify(args.newTaskData);
$.ajax({
type: "POST",
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=add',
data: data,
success: function (data) {
console.log(data);
},
error: function () {
console.log("error")
}
});
if (args.modifiedTaskData) {
updateModifiedTask(args.modifiedTaskData);
}
}
}
});
gantt.appendTo('#Gantt');
function updateModifiedTask(modifiedTask) {
var length = modifiedTask.length, count, currentData;
for (count = 0; count < length; count++) {
currentData = modifiedTask[count];
var data = JSON.stringify(currentData.taskData);
$.ajax({
type: "POST",
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=update',
data: data,
success: function (data) {
console.log(data);
},
error: function () {
console.log("error")
}
});
}
}
</script>

In Server side, new task can be added into database by using add() method.

function add() {  
            $conn = new mysqli("localhost", "root","", "gantt", 3306);  
            $json_del=file_get_contents("php://input");
            $obj_del = json_decode($json_del,true);    
         $key=(int)$obj_del['taskID'];  
         $name=(string)$obj_del['taskName'];
            $startDate=(string)$obj_del['startDate'];
         $endDate=(string)$obj_del['endDate'];
         $duration=(string)$obj_del['duration'];
         $parentID=$obj_del['parentID'];  
         if(!is_null($parentID)){  
          $retval = mysqli_query($conn,"INSERT INTO gantt (taskID, taskName,startDate,endDate,duration,parentID) VALUES ('$key', '$name','$startDate','$endDate','$duration','$parentID')");
          echo json_encode($retval);
         }
         else{
          $retval = mysqli_query($conn,"INSERT INTO gantt (taskID, taskName,startDate,endDate,duration,parentID) VALUES ('$key', '$name','$startDate','$endDate','$duration', NULL)");
          echo json_encode($retval);  
          }
      }

 

2. Update

actionComplete client side event gets triggered while edit task data using cell edit or dialog edit in Gantt. Using this event, we can update the database.

The code snippet to update the database after editing:

<script type="text/javascript">
var gantt = new ej.gantt.Gantt({
actionComplete: function (args) {
if (args.action == "DialogEditing" || args.action == "CellEditing") {
var data = JSON.stringify(args.data.taskData);
$.ajax({
type: "POST",
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=update',
data: data,
success: function (data) {
console.log(data);
},
error: function () {
console.log("error")
}
});
if (args.modifiedRecords) {
updateModifiedTask(args.modifiedRecords);
}
}
}
});
gantt.appendTo('#Gantt');
function updateModifiedTask(modifiedTask) {
var length = modifiedTask.length, count, currentData;
for (count = 0; count < length; count++) {
currentData = modifiedTask[count];
var data = JSON.stringify(currentData.taskData);
$.ajax({
type: "POST",
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=update',
data: data,
success: function (data) {
console.log(data);
},
error: function () {
console.log("error")
}
});
}
}
</script>

In server-side, data can be updated in datasource by using update() method.

function update(){  
$conn = new mysqli("localhost", "root","", "gantt", 3306);   
$json_del=file_get_contents("php://input");
$obj_del = json_decode($json_del,true); 
echo ($obj_del);    
$key=(int)$obj_del['taskID'];  
$name=(string)$obj_del['taskName'];
$startDate=(string)$obj_del['startDate'];
$endDate=(string)$obj_del['endDate'];
$duration=(string)$obj_del['duration'];
$parentID=$obj_del['parentID'];
if(!is_null($parentID)){  
$retval = mysqli_query($conn,"UPDATE gantt SET taskName='$name',startDate='$startDate',endDate='$endDate',duration='$duration',parentID='$parentID' WHERE taskID=$key");
echo json_encode($retval);  
}
else{
$retval = mysqli_query($conn,"UPDATE gantt SET taskName='$name',startDate='$startDate',endDate='$endDate',duration='$duration',parentID= NULL WHERE taskID=$key");
echo json_encode($retval);  
}     
}

 

3. Delete

The actionComplete client side event gets triggered while deleting any task data. Using this event, we can remove the existing record from the database.

The code snippet to remove a task data from database:

<script type="text/javascript">
var gantt = new ej.gantt.Gantt({
actionComplete: function (args) {
if (args.action == "delete") {
var data = JSON.stringify(args.data[0].taskData);
$.ajax({
type: "POST",
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=delete',
data: data,
success: function (data) {
console.log(data);
},
error: function () {
console.log("error")
}
});
if (args.data[0].hasChildRecords) {
deleteChildRecords(args.data[0]);
}
}
}
});
gantt.appendTo('#Gantt');
function deleteChildRecords(data) {
var childRecords = data.childRecords;
var length = childRecords.length, count, currentRecord;
for (count = 0; count < length; count++) {
currentRecord = childRecords[count];
var data = JSON.stringify(currentRecord.taskData);
$.ajax({
type: "POST",
url: 'http://localhost:7777/GanttEJ2/getData.php/?action=delete',
data: data,
success: function (data) {
console.log(data);
},
error: function () {
console.log("error")
}
});
if (currentRecord.hasChildRecords) {
deleteChildRecords(currentRecord);
}
}
}
</script>

In server-side, task data can be delete from database by using delete() method.

function delete()
{   
$conn = new mysqli("localhost", "root","", "gantt", 3306);
$json_del=file_get_contents("php://input");
echo json_encode($json_del);
$obj_del = json_decode($json_del,true);
echo json_encode($json_del);
$key=(int)$obj_del['taskID'];
echo json_encode($key);
$res1 = $conn->query("DELETE FROM `gantt` WHERE taskID=$key");
$success=array("Deleted"=>$key);
echo json_encode($success);
echo json_encode($res1);
}

Sample Link: A sample of EJ2 Gantt with CRUD operation using PHP can be downloaded from following link.

https://www.syncfusion.com/downloads/support/directtrac/general/ze/GanttEJ2-1132142533

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please  to leave a comment
Access denied
Access denied