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.
Implementation of Category Tree Structure with jsTree and PHP:
1) Setting Up Your PHP Project
- Install Xampp from Apache Friends (or any other local server).
- Create new Folder for your Project in XAMPP htdocs directory.
- 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();
- ready.jstree : Triggered when all jsTree Nodes are finished loading.
- loaded.jstree : Triggered after the root node is loaded for the first time
- select_node.jstree : Triggered when an Node is Selected.
- changed.jstree : Triggered when selection changes.
- deselect_node.jstree : Triggered when Node is deselected.
- select_all.jstree : Triggered when all Nodes are selected.
- set_id.jstree : Triggered when Node id value is changed.
- set_text.jstree : Triggered when Node text value is changed.
- delete_node.jstree : Triggered when Node is deleted.
- hide_all.jstree : Triggered when all Nodes are Hidden.
- show_all.jstree : Triggered when all Nodes are Shown.
- hover_node.jstree : Triggered when Node is hovered.
- dehover_node.jstree : Triggered when No Longer hovered.
- disable_checkbox.jstree : Triggered when an node’s checkbox is disabled.
- 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);
}
});
- is_selected : Checks Node is selected or not.
- get_selected : Get an array of all selected nodes.
- get_top_selected : Get an array of all top level selected nodes.
- get_bottom_selected : Get an array of all bottom level selected nodes.
- set_id : Set the Id of Node.
- get_text : Get the text value of Node.
- set_text : Set the text value of Node.
- get_json : gets a JSON representation of a node (or the whole tree).
- hide_icons && show_icons : hide or show the node icons.
- 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
How do I integrate JsTree with PHP?
Integrating JsTree with PHP involves several steps:
- Set up your environment: Ensure you have PHP and JsTree installed.
- Create the database structure: Design your database to store hierarchical data.
- Write PHP scripts: Handle data retrieval and manipulation. Here’s a basic example of PHP code to fetch data for JsTree:
- Complete Guide.
What are some common issues when using JsTree and how do I troubleshoot them?
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”}
]
How can I customize JsTree for a better user experience?
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.
What are the best practices for implementing JsTree in a PHP project?
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.
Can I use JsTree with other JavaScript frameworks or libraries?
Yes, JsTree is versatile and can be integrated with various JavaScript frameworks and libraries, enhancing its functionality and interactivity in your web applications.