Tree Structure with jsTree and PHP

Introduction and Its Benefits:

JsTree is a powerful jQuery plugin that allows us to create dynamic, interactive Category Tree Structure with jsTree and PHP. This makes it ideal for managing hierarchical data, such as Categories and Subcategories, in web applications. The key benefits of using JsTree include its flexibility, easy integration. Whether you’re working with PHP, CodeIgniter, or Laravel JsTree can enhance the user experience by providing an intuitive way to navigate and manage complex data structures.

Category Tree Structure with jsTree and PHP

Implementation of Category Tree Structure with jsTree and PHP:

1) Setting Up Your PHP Project

  1. Install Xampp from Apache Friends (or any other local server).
  2. Create new Folder for your Project in XAMPP htdocs directory.
  3. Download Latest version of JsTree from JsTree Official Website and extract it into your project folder or Use CDNs.
<!-- JsTree theme -->  
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />

<!-- jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>

<!-- JsTree CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

2) Create Database Structure for Categories and Sub Categories

  • Only use one Table, so that you can have unlimited depth of categories (Recommended).
CREATE TABLE categories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    parent_id INT DEFAULT NULL,
    name VARCHAR(255) NOT NULL
);

3) Implementation

  • Add Following Code to your HTML file to Setup JsTree & JQuery using CDNJS.
<?php 
// Convert Your Categories data in this format.
$category_data = [
    [
        "text" => "Category 1",
        "children" => [
            [
                "text" => "Sub Category 1",
                "state" => [
                    "selected" => true
                ]
            ],
            [
                "text" => "Sub Catgeory 2"
            ],
            [
                "text" => "Sub category 3",
                "children" => [
                    ["text" => "Sub Sub Category"]
                ]
            ],
            [
                "text" => "Sub Category 4"
            ]
        ]
    ],
    "Category 2"
];
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>jsTree test</title>
  <!-- JsTree theme -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
</head>
<body>

  <!-- Container Div -->
  <div id="kt_docs_jstree_checkable"></div>

  <!-- jQuery library -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>

  <!-- JsTree CDN -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

  <script>
  $(document).ready(function() {
      var data = <?php echo json_encode($data); ?>;
      
      $('#kt_docs_jstree_checkable').jstree({
          'plugins': ["checkbox", "types"],
          'core': {
              "themes": {
                  "responsive": false,
                  'icons': false
              },
              'multiple': true,  // Keep multiple true for checkboxes

              // Data Format You need to pass according below format
              'data': data
          },
          "types": {
              "default": {
                  "icon": ""
              },
              "file": {
                  "icon": ""
              }
          }
      });

      // Custom event handler for single checkbox selection
      $('#kt_docs_jstree_checkable').on('changed.jstree', function (e, data) {
          if (data.action === 'select_node') {
              var selectedNodes = data.instance.get_selected();

              // Deselect all nodes except the one just selected
              if (selectedNodes.length > 1) {
                  var lastSelectedNode = data.node.id;
                  data.instance.deselect_all(true);
                  data.instance.select_node(lastSelectedNode);
              }
          }
      });
  });
  </script>
</body>
</html>

By following this comprehensive guide, you’ll be able to effectively implement a Category Tree Structure with jsTree and PHP. This will not only enhance the user experience but also make managing hierarchical data more intuitive and efficient.

jsTree Events:

jsTree triggers various events on the div / container.

$('#kt_docs_jstree_checkable')
  // listen for event
  .on('changed.jstree', function (e, data) {
    var i, j, r = [];
    for(i = 0, j = data.selected.length; i < j; i++) {
      r.push(data.instance.get_node(data.selected[i]).text);
    }
    $('#event_result').html('Selected: ' + r.join(', '));
  })
  // create the instance
  .jstree();
  1. ready.jstree : Triggered when all jsTree Nodes are finished loading.
  2. loaded.jstree : Triggered after the root node is loaded for the first time
  3. select_node.jstree : Triggered when an Node is Selected.
  4. changed.jstree : Triggered when selection changes.
  5. deselect_node.jstree : Triggered when Node is deselected.
  6. select_all.jstree : Triggered when all Nodes are selected.
  7. set_id.jstree : Triggered when Node id value is changed.
  8. set_text.jstree : Triggered when Node text value is changed.
  9. delete_node.jstree : Triggered when Node is deleted.
  10. hide_all.jstree : Triggered when all Nodes are Hidden.
  11. show_all.jstree : Triggered when all Nodes are Shown.
  12. hover_node.jstree : Triggered when Node is hovered.
  13. dehover_node.jstree : Triggered when No Longer hovered.
  14. disable_checkbox.jstree : Triggered when an node’s checkbox is disabled.
  15. enable_checkbox.jstree : Triggered when an node’s checkbox is enabled.

You can review the list of all events to know what to listen for.

jsTree Methods:

The example shows how to obtain a reference and invoke a method.

// Custom event handler for single checkbox selection
$('#kt_docs_jstree_checkable').on('changed.jstree', function (e, data) {
    if (data.action === 'select_node') {
        var selectedNodes = data.instance.get_selected();

        // Deselect all nodes except the one just selected
        if (selectedNodes.length > 1) {
            var lastSelectedNode = data.node.id;
            data.instance.deselect_all(true);
            data.instance.select_node(lastSelectedNode);
        }

        // Check if a specific node is selected
        var isSelected = data.instance.is_selected(data.node.id);
        console.log("Node " + data.node.text + " is selected: " + isSelected);
    }
});
  1. is_selected : Checks Node is selected or not.
  2. get_selected : Get an array of all selected nodes.
  3. get_top_selected : Get an array of all top level selected nodes.
  4. get_bottom_selected : Get an array of all bottom level selected nodes.
  5. set_id : Set the Id of Node.
  6. get_text : Get the text value of Node.
  7. set_text : Set the text value of Node.
  8. get_json : gets a JSON representation of a node (or the whole tree).
  9. hide_icons && show_icons : hide or show the node icons.
  10. hide_checkboxes && show_checkboxes : hide or show the node checkbox icons.

Check for a list of available methods in jsTree.

JSON Formats:

Using Different JSON Format’s.

// Expected format of the node (there are no required fields)
{
  id          : "string" // will be autogenerated if omitted
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  children    : []  // array of strings or objects
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}

// Alternative format of the node (id & parent are required)
{
  id          : "string" // required
  parent      : "string" // required
  text        : "string" // node text
  icon        : "string" // string for custom
  state       : {
    opened    : boolean  // is the node open
    disabled  : boolean  // is the node disabled
    selected  : boolean  // is the node selected
  },
  li_attr     : {}  // attributes for the generated LI node
  a_attr      : {}  // attributes for the generated A node
}
// Using JSON
$('#using_json').jstree({ 'core' : {
    'data' : [
       'Simple root node',
       {
         'text' : 'Root node 2',
         'state' : {
           'opened' : true,
           'selected' : true
         },
         'children' : [
           { 'text' : 'Child 1' },
           'Child 2'
         ]
      }
    ]
} });

// Using the alternative JSON format
$('#using_json_2').jstree({ 'core' : {
    'data' : [
       { "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
       { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
       { "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
       { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
    ]
} });

Using AJAX:

$('#tree').jstree({
'core' : {
  'data' : {
    'url' : function (node) {
      return node.id === '#' ?
        'ajax_roots.json' :
        'ajax_children.json';
    },
    'data' : function (node) {
      return { 'id' : node.id };
    }
  }
});

Using a function:

$('#tree').jstree({
    'core' : {
        'data' : function (obj, cb) {
            cb.call(this,
              ['Root 1', 'Root 2']);
        }
    }});

Conclusion

In this guide, we explored how to implement a Category Tree Structure with jsTree and PHP. By integrating the JsTree (jQuery plugin) with php and frameworks like CodeIgniter and Laravel, we can create an hierarchical data representation. We covered the configuration to prevent multiple selections, and customized it to hide default icons. This powerful tool simplifies the management and presentation of nested categories, enhancing the user experience in both simple and complex applications. If you are working on a basic HTML project or a Complex PHP application, this approach offers a strong solution for handling Category Tree Structure with jsTree and PHP efficiently.

FAQ’s

Integrating JsTree with PHP involves several steps:

  1. Set up your environment: Ensure you have PHP and JsTree installed.
  2. Create the database structure: Design your database to store hierarchical data.
  3. Write PHP scripts: Handle data retrieval and manipulation. Here’s a basic example of PHP code to fetch data for JsTree:
  4. Complete Guide.

Common issues with JsTree include incorrect data formatting, script conflicts, and rendering problems. Troubleshoot by:

  • Checking your JavaScript console for errors.
  • Ensuring your data is correctly formatted for JsTree.
  • Debugging using browser tools.
  • For example, ensure your data format:

Example :

[
{“id”: “1”, “parent”: “#”, “text”: “Root”},
{“id”: “2”, “parent”: “1”, “text”: “Child”}
]

JsTree offers various customization options such as themes, plugins, and event handlers. For a better user experience:

  • Use themes to style your tree.
  • Add plugins for additional functionality.
  • Handle events to customize behavior.
  • Complete Guide.

Best practices for implementing a Category Tree Structure with JsTree and PHP include:

  • Organizing your codebase.
  • Securing your data interactions.
  • Optimizing performance.
  • Ensuring compatibility across browsers and devices.

Yes, JsTree is versatile and can be integrated with various JavaScript frameworks and libraries, enhancing its functionality and interactivity in your web applications.

Leave a Comment