Saturday, June 6
Shadow

Tutorial – Drag and Drop Reorder Images in CodeIgniter

The draggable feature is very useful to integrate Drag and Drop functionality in the web application. jQuery UI provides an easy way to enable the draggable feature on any DOM element. With jQuery draggable functionality, the elements can be moved by drag & drop using the mouse. You can use the drag and drop functionality to reorder the objects dynamically using jQuery UI draggable feature. The drag and drop feature is the best option to make the reorder list user-friendly.

Loading...

If you want to control the listing order of the images dynamically, the order should be maintained by the database. In this tutorial, we will show you how to use drag and drop feature to integrate reorder images functionality in CodeIgniter. The example script will use the jQuery UI library and Ajax to rearrange images order and save list order in the database.

The following functionality will be implemented to integrate drag and drop reorder images in CodeIgniter.

  • Fetch the images from the database and list them on the web page.
  • Use the jQuery UI sortable() method to enable draggable functionality on the DOM element.
  • Drag and drop images to rearrange the order of the images.
  • Save image order to the database using jQuery and Ajax.
  • List the images as per the listing order.

Drag and Drop Reorder Images using jQuery, Ajax, PHP & MySQL

Before getting started, take a look at the file structure of the sample CodeIgniter Drag & Drop Image Reorder application.

codeigniter_drag_drop_reorder_images/
├── application/
│   ├── controllers/
│   │   └── Drag_drop.php
│   ├── models/
│   │   └── Image.php
│   └── views/
│       └── drag_drop/
│           └── index.php
└── assets/
    ├── js/
    │   │── jquery.min.js
    │   └── jquery-ui.min.js
    ├── css/
    │   └── style.css
    └── images/

Create Database Table

To store the file information and image order, a table is required in the database. The following SQL creates an images table with some basic fields in the MySQL database.

CREATE TABLE `images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `file_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
 `img_order` int(5) NOT NULL DEFAULT 0,
 `created` datetime NOT NULL,
 `modified` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Controller (Drag_drop.php)

The Drag_Drop controller handles the image listing and order update functionality.

  • __construct()
    • Loads Image model that helps to fetch and update image file info into the database.
  • index()
    • Fetch all images from the database using the getRows() method of the Image model.
    • Pass images data to the view.
  • orderUpdate()
    • Retrieve the ID of the images from the AJAX POST request.
    • Update image order in the database using the update() method of the Image model.
<?php 
defined
('BASEPATH"http://www.codexworld.com/) OR exit('No direct script access allowed"http://www.codexworld.com/);

class 

Drag_Drop extends CI_Controller {
    function  
__construct() {
        
parent::__construct();
        
        
// Load file model
        
$this->load->model('image"http://www.codexworld.com/);
    }
    
    function 
index(){
        
$data = array();
        
        
// Get images data from the database
        
$data['images"http://www.codexworld.com/] = $this->image->getRows();
        
        
// Pass the images data to view
        
$this->load->view('drag_drop/index"http://www.codexworld.com/$data);
    }
    
    function 
orderUpdate(){
        
// Get id of the images
        
$ids $this->input->post('ids"http://www.codexworld.com/);
        
        if(!empty(
$ids)){
            
// Generate ids array
            
$idArray explode(","http://www.codexworld.com/$ids);
            
            
$count 1;
            foreach (
$idArray as $id){
                
// Update image order by id
                
$data = array('img_order' => $count);
                
$update $this->image->update($data$id);
                
$count ++;    
            }
            
        }
        
        return 
true;
    }
}

Model (Image.php)

The Image model handles the database related operations (fetch and update).

  • __construct() – Define the table name where the images data will be stored.
  • getRows()
    • Fetch the file’s data from the database based on the image order.
  • update()
    • Update image order into the database using the update() function of CodeIgniter Query Builder Class.
<?php  
defined
('BASEPATH"http://www.codexworld.com/) OR exit('No direct script access allowed"http://www.codexworld.com/);

class 

Image extends CI_Model{
    function 
__construct() {
        
$this->tableName 'images"http://www.codexworld.com/;
    }
    
    
/*
     * Fetch files data from the database
     * @param id returns a single record if specified, otherwise all records
     */
    
public function getRows($id '"http://www.codexworld.com/){
        
$this->db->select('*"http://www.codexworld.com/);
        
$this->db->from($this->tableName);
        
$this->db->order_by('img_order"http://www.codexworld.com/'asc"http://www.codexworld.com/);
        
$query $this->db->get();
        return (
$query->num_rows() > 0)?$query->result_array():false;
    }
    
    
/*
     * Update file data into the database
     * @param array the data for inserting into the table
     * @param int the row id
     */
    
public function update($data = array(), $id){
        if(!
array_key_exists('modified"http://www.codexworld.com/$data)){
            
$data['modified"http://www.codexworld.com/] = date("Y-m-d H:i:s"http://www.codexworld.com/);
        }
        
$update $this->db->update($this->tableName$data, array('id' => $id));
        return 
$update?true:false;
    }
}

View (drag_drop/index.php)

Include the jQuery and jQuery UI library.

<script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery-ui.min.js"></script>

The following JavaScript code helps to enable the jQuery UI Draggable and Sortable functionality.

  • Attach the sortable() method to the image elements.
  • On Save Order request, POST the order of the images to the server-side script (drag_drop/orderUpdate) using Ajax to update image order in the database.
  • After the response is received, reload the page with updated listing order.
<script>
$(document).ready(function(){
    $('.reorder_link').on('click',function(){
        $("ul.reorder-photos-list").sortable({ tolerance: 'pointer' });
        $('.reorder_link').html('save reordering');
        $('.reorder_link').attr("id","saveReorder");
        $('#reorderHelper').slideDown('slow');
        $('.image_link').attr("href","javascript:void(0);");
        $('.image_link').css("cursor","move");
        $("#saveReorder").click(function( e ){
            if( !$("#saveReorder i").length ){
                $(this).html('').prepend('<img src="http://www.codexworld.com/<?php echo base_url('assets/images/refresh-animated.gif"http://www.codexworld.com/); ?>"/>');
                $("ul.reorder-photos-list").sortable('destroy');
                $("#reorderHelper").html("Reordering Photos - This could take a moment. Please don't navigate away from this page.").removeClass('light_box').addClass('notice notice_error');
	
                var h = [];
                $("ul.reorder-photos-list li").each(function() {
                    h.push($(this).attr('id').substr(9));
                });
				
                $.ajax({
                    type: "POST",
                    url: "<?php echo base_url('drag_drop/orderUpdate"http://www.codexworld.com/); ?>",
                    data: {ids: " " + h + ""},
                    success: function(){
                        window.location.reload();
                    }
                });	
                return false;
            }	
            e.preventDefault();		
        });
    });
});
</script>

Initially, all the images are fetched from the Drag_Drop controller and listed as per the order specified in the img_order field of images table.

  • Once the reorder link is clicked, the drag & drop feature is enabled to sort the image list.
  • The user can rearrange the order of the images by drag & drop.
  • On clicking the Save Reorder button, the order of the images is sent to the orderUpdate() method of the Drag_Drop controller using jQuery Ajax for updating the list order in the database.
<a href="javascript:void(0);" class="reorder_link" id="saveReorder">reorder photos</a>
<div id="reorderHelper" class="light_box" style="display:none;">1. Drag photos to reorder.<br>2. Click 'Save Reordering' when finished.</div>
<div class="gallery">
    <ul class="reorder_ul reorder-photos-list">
    <?php 
    
if(!empty($images)){
        foreach(
$images as $row){
    
?> <li id="image_li_<?php echo $row['id"http://www.codexworld.com/]; ?>" class="ui-sortable-handle"> <a href="javascript:void(0);" style="float:none;" class="image_link"> <img src="http://www.codexworld.com/<?php echo base_url('assets/images/"http://www.codexworld.com/.$row["file_name"http://www.codexworld.com/]); ?>"/> </a> </li>     <?php } } ?> </ul> </div>

Drag and Drop File Upload with Dropzone in Codeigniter

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

(Visited 1 times, 1 visits today)