Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Drag, Drop , Sort and Save using jquery in cakephp

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.86k
    Comment on it

    To implement drag and drop in cakephp using jquery, you need to follow following steps :-

    Step 1: Make index.ctp and add following code in it :-

    <head>
    	<style>
    		#sortable-list		{ padding:0; }
    		#sortable-list li	{ padding:4px 8px; color:#000; cursor:move; list-style:none; width:500px; background:#ddd; margin:10px 0; border:1px solid #999; }
    		#message-box		{ background:#fffea1; border:2px solid #fc0; padding:4px 8px; margin:0 0 14px 0; width:500px; }
    	</style>
    	<link href="<?php echo $this->webroot; ?>css/jquery-ui.css" rel="stylesheet">
    	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    	<script src="<?php echo $this->webroot; ?>js/jquery.js"></script>
    	<script src="<?php echo $this->webroot; ?>js/jquery-ui.js"></script>
    </head>
    <?php 
    
    if (!empty($result)) {
    	?>
    	
    	<p>Drag and drop the elements below.  The database gets updated on every drop.</p>
    
    	<div id="message-box"><?php echo @$message; ?> Waiting for sortation submission...</div>
    
    	<?php echo $this->Form->create(null, array('url'=>array('controller'=>'users','action'=>'saveOrder'),'id'=>'dd-form')); ?>
    	
    		<p>
    			<input type="checkbox" value="1" name="autoSubmit" id="autoSubmit" <?php if (@$_POST['autoSubmit']) {echo 'checked="checked"';}?> 
    			<label for="autoSubmit">Automatically submit on drop event</label>
    		</p>
    
    		<ul id="sortable-list">
    			<?php
    			$order = array();
    
    			foreach ($result as $key => $value) {
    				echo '<li title="', $value['User']['id'], '">', $value['User']['title'], '</li>';
    				$order[] = $value['User']['id'];
    			}
    			
    			?>
    		</ul>
    		<br />
    		<input type="hidden" name="sort_order" id="sort_order" value="<?php echo implode(',', $order); ?>" />
    		<input type="submit" name="do_submit" value="Submit Sortation" class="button" />
    	<?php echo $this->Form->end(); ?>
    	<?php } else {?>
    
    	<p>Sorry!  There are no items in the system.</p>
    
    	<?php }?>
    
    	<?php
    	
    	?>
    
    	<script type="text/javascript">
    		$(document).ready(function() {
    			/* grab important elements */
    			var sortInput = jQuery('#sort_order');
    			console.log(sortInput);
    			var submit = jQuery('#autoSubmit');
    			var messageBox = jQuery('#message-box');
    			var list = jQuery('#sortable-list');
    			/* create requesting function to avoid duplicate code */
    			var request = function() {
    				$.ajax({
    					beforeSend: function() {
    						messageBox.text('Updating the sort order in the database.');
    					},
    					complete: function() {
    						messageBox.text('Database has been updated.');
    					},
    			data: 'sort_order=' + sortInput[0].value + '&ajax=' + submit[0].checked + '&do_submit=1&byajax=1', //need [0]?
    			type: 'post',
    			url: '/dragdrop/users/saveOrder'
    		});
    			};
    			/* worker function */
    			var fnSubmit = function(save) {
    		//alert(save);
    		var sortOrder = [];
    		list.children('li').each(function(){
    			sortOrder.push(jQuery(this).data('id'));
    		});
    		sortInput.val(sortOrder.join(','));
    		console.log(sortInput.val());
    		if(save) {
    			request();
    		}
    	};
    	/* store values */
    	list.children('li').each(function() {
    		var li = jQuery(this);
    		li.data('id',li.attr('title')).attr('title','');
    	});
    	/* sortables */
    	list.sortable({
    		opacity: 0.7,
    		update: function() {
    			fnSubmit(submit[0].checked);
    		}
    	});
    	list.disableSelection();
    	/* ajax form submission */
    	jQuery('#dd-form').bind('submit',function(e) {
    		if(e) e.preventDefault();
    		fnSubmit(true);
    	});
    });
    	</script>

    Step 2: Make UsersController.php, and add the following in it:-

    
    	<?php
    
    App::uses('Controller', 'Controller');
    
    class UsersController extends AppController {
    
    	public function index()
    
    	{
    		$result = $this->User->find('all', array('fields'=>array('id','title'),'order'=>'sort_order ASC'));
    		$this->set("result",$result);
    
    	}
    	public function change(){
    
    	}
    
    	public function saveOrder() {
    
    		$this->layout = null;
    		if ($this->request->is('post'))
    		{
    			
    			$ids = explode(",", $this->request->data['sort_order']);
    			//print_r($ids); die;
    			/* run the update query for each id */
    			foreach ($ids as $index => $id) {
    				if (isset($id) && !empty($id)) {
    					$query = 'UPDATE users SET sort_order = ' . ($index + 1) . ' WHERE id = ' . $id;
    					//$result = mysql_query($query) or die(mysql_error() . ': ' . $query);
    					$data['id'] = $id;
    				  	$data['sort_order'] = $index + 1;
    
    				 	$this->User->id = $data['id'];
    
    				 	if($this->User->saveField('sort_order', $data['sort_order'])) {
    				  		echo $query.'<br/>';
    				 	}else {
    				  		die('Error, insert query failed');
    				  	} 
    				}
    
    			}
    			die;
    		}
    	}
    }
    
    

    Step3: Make User.php model :-

    
    <?php
    App::uses('AppModel', 'Model');
    class User extends AppModel {
    }
    
    ?>

    Step 4: Create the following database table and insert the values in it:-

    CREATE TABLE IF NOT EXISTS `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(225) NOT NULL,
      `sort_order` int(11) NOT NULL,
      `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
      PRIMARY KEY (`id`)
    );
    
    
    INSERT INTO `users` (`id`, `title`, `sort_order`, `created`) VALUES
    (1, 'Article1', 1, '0000-00-00 00:00:00'),
    (2, 'Article2', 2, '0000-00-00 00:00:00'),
    (3, 'Article3', 3, '0000-00-00 00:00:00'),
    (4, 'Article4', 4, '0000-00-00 00:00:00'),
    (5, 'Article5', 5, '0000-00-00 00:00:00');

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: