Create Treeview with jsTree plugin and PHP

If you already managing the relationship between parent and child items using a separate field then it is easier to create a hierarchical structure.

With the use of a jsTree plugin, this will be created in less time.

jsTree is a jQuery plugin that creates a hierarchical data structure using JSON data.

It allows setting icon of a node, by default open, disable a node and set it selected while initializing, etc.

In this tutorial, I show how you can make a tree structure of MySQL data using jsTree plugin and PHP.

Create treeview with jsTree plugin and PHP


Contents

  1. Table
  2. Configuration
  3. Download & Include
  4. HTML & PHP
  5. jQuery
  6. Demo
  7. Conclusion

1. Table

I am using folders table in the example –

CREATE TABLE `folders` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(80) NOT NULL,
  `parentid` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

It has the following data –

INSERT INTO `folders` (`id`, `name`, `parentid`) VALUES
(1, 'Folder1', 0),
(2, 'Folder2', 0),
(3, 'Folder 1 sub1', 1),
(4, 'Folder 1 sub1.1', 3),
(5, 'Folder 1 sub1.2', 3),
(6, 'Folder 1 sub1.1.1', 4),
(7, 'Folder 1 sub2', 1),
(8, 'Folder 1 sub3', 1),
(9, 'Folder 1 sub3.1', 8),
(10, 'Folder 2 sub1', 2),
(11, 'Folder 2 sub1.1', 10),
(12, 'Folder 2 sub1.2', 10),
(13, 'Folder 2 sub2', 2),
(14, 'Folder 3', 0);

I stored parent id value in parentid field.


2. Configuration

Create config.php for the database connection.

Completed Code

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}

3. Download & Include

  • Download the jsTree plugin from the official website.
  • Include jsTree style.min.css, jQuery library, and jstree.min.js file.
<link rel="stylesheet" type="text/css" href="jstree/dist/themes/default/style.min.css">

<script src="jquery-3.4.1.min.js"></script>

<script type="text/javascript" src="jstree/dist/jstree.min.js"></script>

Or you can use CDN –

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

4. HTML & PHP

Fetch all records from folders table and loop on it.

JSON data syntax –

{
   "id": [id], 
   "parent": [parentid], 
   "text": [text],
   "state": {
      "selected": [boolean-value],
      "opened": [boolean-value]
   }
}

NOTE – If parent id is 0 then pass ‘#’.

With PHP create an Array and encode in JSON format.

If $parentid is equals to 0 then assign ‘#’ to $parentid.

For setting a node with $id == 2 selected and opened pass true to $selected and $opened variables.

Initialize $folders_arr Array with id, parent, text, and state keys.

Create <div id='folder_jstree'> to initialize jsTree and <textarea id='txt_folderjsondata' > to store $folders_arr Array in JSON format.

Completed Code

<?php 
include "config.php";
?>

<!DOCTYPE html>
<html>
<head>
   <title>Create Treeview with jsTree plugin and PHP</title>

   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
</head>
<body>
   <?php 
   $folderData = mysqli_query($con,"SELECT * FROM folders");

   $folders_arr = array();
   while($row = mysqli_fetch_assoc($folderData)){
      $parentid = $row['parentid'];
      if($parentid == '0') $parentid = "#";

      $selected = false;$opened = false;
      if($row['id'] == 2){
         $selected = true;$opened = true;
      }
      $folders_arr[] = array(
         "id" => $row['id'],
         "parent" => $parentid,
         "text" => $row['name'],
         "state" => array("selected" => $selected,"opened"=>$opened) 
      );
   }

   ?>

   <!-- Initialize jsTree -->
   <div id="folder_jstree"></div>

   <!-- Store folder list in JSON format -->
   <textarea id='txt_folderjsondata'><?= json_encode($folders_arr) ?></textarea>

</body>
</html>

5. jQuery

Read value from #txt_folderjsondata and convert it into a JSON object and assign in folder_jsondata.

Initialize jstree on #folder_jstree.

Pass folder_jsondata in core data option. Using multiple option disable multiple node selection by setting it to false.

Completed Code

$(document).ready(function(){
   var folder_jsondata = JSON.parse($('#txt_folderjsondata').val());

   $('#folder_jstree').jstree({ 'core' : {
      'data' : folder_jsondata,
      'multiple': false
   } });

});

6. Demo

View Demo


7. Conclusion

If parentid is equaled to 0 then assign ‘#’ to parent key.

You need to pass JSON data in a specified format otherwise it will not initialize.

If you found this tutorial helpful then don't forget to share.