Tutorial: Organization Chart

In this tutorial we will see the steps that must be followed to create an organization chart.

For this example, we will use 3 applications, the first, a blank that will display the organization chart, a second blank that will be executed via Ajax to perform the updates in the database, and finally, a form application that will be displayed in modal for editing the employee data.

Creating the Form

1 – Create a new Form application based on the “employees” table.

2 – Access the SQL option and add a WHERE clause to the application: employee_id = [empkey]

3 – Once we are going to call this application to be opened in a modal window, we will use a device to close it automatically after changing the data, and reload the previous application. To do this, access the menu “Programming >> Javascript Methods >> New Method“, where we will create a Javascript function named “upd_parent“, with the code: 

window.parent.location.reload ();

4 – Access now the menu “Form >> Events >> onAfterUpdate” and call the Javascript function that we created, and repeat the procedure for the onAfterDelete event.

sc_ajax_javascript ('upd_parent'); 

5 – Access the onApplicationInit event to include a validation code for the empkey variable .

if (isset ($ _ GET [“empkey”])) {[empkey] = $ _GET [“empkey”]; }

6 – Generate the source code of the application.

Creating the Ajax application

We will now create one more secondary application, which will be complementary to our main application. This will be an application just to execute insert, update and delete commands via Ajax.

1 – Create a new Blank application

2 – In the OnExecute event we add the following code:

// UPDATE NODES
if( $_POST['ajaxtp'] == 'save' ){
	
	$var_sql_upd = "UPDATE example_gojs SET ";
	
	if( $_POST['item_mode'] == "updtext" ){
		$var_sql_upd .= " employee_name = '".$_POST['item_value']."' ";
	}
	elseif( $_POST['item_mode'] == "updparent" ){
		$var_sql_upd .= " employee_boss = ".$_POST['item_value'];
	}
	$var_sql_upd .= " WHERE employee_id = ". $_POST['item_id'];
	echo $var_sql_upd;
	sc_exec_sql( $var_sql_upd );
}

//INSERT A NODE
elseif( $_POST['ajaxtp'] == 'insert' ){ 

	$today = date("Y-m-d");
	
	if( $_POST['empboss'] == 0 ) { 
		$sql_insert = "INSERT INTO example_gojs(employee_name, employee_title, employee_photo) VALUES ('(new person)', '(title)', 'grp__NM__img__NM__me.png')";
	}else{
		$sql_insert = "INSERT INTO example_gojs(employee_name, employee_title, employee_boss, employee_photo) VALUES ('(new person)', '(title)', ".$_POST['empboss'].", 'grp__NM__img__NM__me.png')";
	}
	sc_exec_sql($sql_insert);
			
	sc_lookup(rs,"SELECT employee_id FROM example_gojs ORDER BY employee_id DESC LIMIT 1");
	$result = {rs[0][0]};
	echo $result;

}

//DELETE A NODE
elseif( $_POST['ajaxtp'] == 'delete' ){ 
	$sql_delete = "DELETE FROM example_gojs WHERE employee_id = ".$_POST['empkey'];
	sc_exec_sql($sql_delete);
}

3 – Generate the source code of the application.

Creating the Organization Chart

Finally we will create our main application where we will build and display the organization chart.

1 – Create a new Blank application

2 – In the OnExecute event we add the following code

function chkChildren($empkey){
	$chk_sql = "SELECT COUNT(*) FROM example_gojs WHERE employee_boss=".$empkey;
	sc_lookup(rs, $chk_sql);	
	return {rs[0][0]};
}
function getChildren($empid, $str_ret, $level){
	
	if($empid==0){
		$check_sql = "SELECT employee_id, employee_name, employee_title, employee_boss, employee_photo FROM example_gojs WHERE employee_boss IS NULL OR employee_boss = 0";
	}else{
		$check_sql = "SELECT employee_id, employee_name, employee_title, employee_boss, employee_photo FROM example_gojs WHERE employee_boss=".$empid;
	}	
    sc_lookup(result, $check_sql);	
	$counter = count({result});	
	
    for($i=0;$i<$counter;$i++){ 
		if ( substr({result[$i][4]}, 0, 7) == 'grp__NM'){ 
			$urlimg =  "../_lib/img/".{result[$i][4]}; // Just for the purpose of example. Gets the project directory path
		}else{
			$urlimg = "../../../file/img/" .{result[$i][4]}; // Image upload. It gets from the images directory path
		}
		if( $level>4 ) { $level = 4; }
		
		$str_ret .= " { 'key': '".{result[$i][0]}."', 'title': '".{result[$i][1]}."',	'content': '".{result[$i][2]}."', 'picture': '".$urlimg."',	'className': 'level-".$level."' ";
		
		$haschildren = chkChildren({result[$i][0]});		
		
		if($haschildren > 0 ){ 
			$str_ret .=  ",	'children': [";	
			$level++;
			$str_ret = getChildren({result[$i][0]}, $str_ret, $level);
			$level--;
			$str_ret = substr($str_ret, 0, -1);
			$str_ret .=  "]";
		}
		
		$str_ret .=  "},";
	}	
	return $str_ret;
}

$var_nodes_array = 'var datasource = ';
$nodes = '';
$nodes = getChildren(0,$nodes,1);

$var_nodes_array .= substr($nodes, 0, -1);
 
$var_nodes_array .= ';';
//echo $var_nodes_array;
?>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Organogram</title>
	
	sc_include_lib("Jquery");
	sc_include_lib("jquery_thickbox");
	sc_include_lib("orgchart");
	
	<style> html, body{ background-color: #F9FAFC; } </style> 
	
	
	
</head>
<body>
	<div id="organogram"> </div>		
	<script type="text/javascript">
		$(function() {

		var getId = function() {
			return (new Date().getTime()) * 1000 + Math.floor(Math.random() * 1001);
		};

		var nodeSelected = null;
					
		<?php echo $var_nodes_array; ?>

		var nodeTemplate = function(data) {
			return '<div class="node-picture"><img width="50px" src="' + (data.picture ? data.picture : 'http://placehold.it/48/?text=%')  + '"></div><div class="node-content"><div class="node-title">' + data.title + '</div>' + data.content + '</div>';
		};

		var template = [];

		var oc = $('#organogram').orgchart({
			'data' : datasource,
			'nodeTemplate': nodeTemplate,
			'draggable': true,
			'createNode': function(nodeSelected, data) {
				nodeSelected[0].id = data.key; //getId();
			},
			  'dropCriteria': function($draggedNode, $dragZone, $dropZone) {
				
				return true;
			  }
		}); 
		
		oc.$chart.on('nodedrop.orgchart', function(event, nodeSelected) {
			var droppednode = nodeSelected.draggedNode[0].id;
			var parentnode =  nodeSelected.dropZone.parent().closest('table').find('.node')[0].id;
			console.log('draggedNode:' + droppednode + ', Parent:' + parentnode
			//+ ', dragZone:' + event.dragZone.children('.title').text()
			//+ ', dropZone:' + event.dropZone.children('.title').text()
		  );
			save(droppednode, 'updparent', parentnode);
		});

		$('.node').append('<div class="node-menu"><em></em><em></em><em></em><ul><li class="edit-item"><a href="#"><?php echo {lang_context_menu_edit}; ?></a></li><li class="divider"></li><li class="add-children"><a href="#"><?php echo {lang_context_menu_add_child}; ?></a></li><li class="add-sibling"><a href="#"><?php echo {lang_context_menu_add_sibling}; ?></a></li><li class="divider"></li><li class="del-item"><a href="#"><?php echo {lang_context_menu_rem}; ?></a></li></ul></div>');

		$('.node-menu').click(function(){
			$(this).toggleClass('active');
			nodeSelected = $(this).parent();
		});

		$('.add-children a').click(function(e){
			e.preventDefault();

			var hasChild = nodeSelected.parent().attr('colspan') > 0 ? true : false;
			var nodeVals = [];
			var template = [{'title': ' ', 'content': ' ', 'className': 'level-2', 'relationship': rel, 'id': getId()}]

			if (!hasChild) {
				var rel = nodeVals.length > 1 ? '110' : '100';
				oc.addChildren(nodeSelected, template);
			} else {
				oc.addSiblings(nodeSelected.closest('tr').siblings('.nodes').find('.node:first'), template);
			}
			
			insertNode(nodeSelected[0].id);
		})

		$('.add-sibling a').click(function(e){
			e.preventDefault();

			var template = [{'title': ' ', 'content': ' ', 'className': 'level-2', 'id': getId()}]

			oc.addSiblings(nodeSelected, template); 
			
			insertNode(nodeSelected.parent().closest('table').parent().closest('table').find('.node')[0].id);
		})
			
		$('.edit-item a').click(function(e){
			var strAppEdit = 'org_chart_form';
			tb_show('', '../'+ strAppEdit +'/?empkey='+nodeSelected[0].id+'&KeepThis=true&TB_iframe=true&height=600&width=600', null);
		})

		$('.del-item a').click(function(e){
			e.preventDefault();
			oc.removeNodes(nodeSelected);
			
			deleteNode(nodeSelected[0].id);
		})
		
			
		function insertNode(node_id) { 	
		  $.post( "../org_chart_ajax/index.php",
				{ ajaxtp: "insert", empboss: node_id })
				.done(function(response,status){			
					return response;	  		
				});
			window.location.reload(); 
		}
			
		function save(v_id, v_mode, v_value) { 
			var val = v_value;
			if ( v_mode == "updstep") { val = v_value.substring(5); }
			$.post( "../org_chart_ajax/index.php",
				{ ajaxtp: "save", item_id: v_id, item_mode: v_mode, item_value: val },
				function(response, status){
					return response;
				}
			);
		}	
			
		function deleteNode(node_id) { 	
		  $.post( "../org_chart_ajax/index.php",
				{ ajaxtp: "delete", empkey: nodeSelected[0].id },
				function(response, status){
					return response;
				}
			);
		}

	});
	</script>
</body>
</html>
<?php


Note that in the code we are including native Scriptcase libraries.
Specifically for the construction of the Organization Chart, we need the “orgchart” library.

        sc_include_lib("Jquery");
	sc_include_lib("jquery_thickbox");
	sc_include_lib("orgchart");


Also notice the calls to the form and Ajax applications.

3 – Finally we run the application

Tutorials in the same category

Tutorial: Cloud File Management

Some of the data storage services are ready to securely read and store files and images from your S...

Integration with WhatsApp

To integrate WhatsApp with ScriptCase, we will be using a specific API called Chat-API, it is a...

Tutorial: Blank Application

In this example a Blank application will be created, using for example jquery code to create an acc...

Using the Paypal and Pagseguro API

1 - We create an application of the grid type 2 - We edit the following fields and create a ...

Comment this post