Code:
<?php defined('BASEPATH') OR exit('No direct script access allowed.');
/**
* @author Ivan Tcholakov <[email protected]>, 2014
* @license The MIT License, http://opensource.org/licenses/MIT
*/
if (!function_exists('display_order_up')) {
function display_order_up($table, $id, $param = null) {
if (is_object($table)) {
$table = $table->table();
}
$table = ci()->db->escape_str($table);
$sql = "SELECT
t1.id,
t1.display_order,
t2.display_order AS display_order_2
FROM
".$table." AS t1,
".$table." AS t2
WHERE
t2.id='".ci()->db->escape_str($id)."' AND
t1.display_order < t2.display_order";
if (isset($param)) {
$sql .= " AND ".$param;
}
$sql .= " ORDER BY
t1.display_order DESC
LIMIT
1";
$row = ci()->db
->query($sql)
->row_array();
if (!empty($row)) {
$id_1 = $row['id'];
$display_order_1 = $row['display_order'];
$id_2 = $id;
$display_order_2 = $row['display_order_2'];
ci()->db
->set('display_order', $display_order_1)
->where('id', $id_2)
->update($table);
ci()->db
->set('display_order', $display_order_2)
->where('id', $id_1)
->update($table);
}
}
}
if (!function_exists('display_order_down')) {
function display_order_down($table, $id, $param = null) {
if (is_object($table)) {
$table = $table->table();
}
$table = ci()->db->escape_str($table);
$sql = "SELECT
t1.id,
t1.display_order,
t2.display_order AS display_order_2
FROM
".$table." AS t1,
".$table." AS t2
WHERE
t2.id='".ci()->db->escape_str($id)."' AND
t1.display_order > t2.display_order";
if (isset($param)) {
$sql .= " AND ".$param;
}
$sql .= " ORDER BY
t1.display_order ASC
LIMIT
1";
$row = ci()->db
->query($sql)
->row_array();
if (!empty($row)) {
$id_1 = $row['id'];
$display_order_1 = $row['display_order'];
$id_2 = $id;
$display_order_2 = $row['display_order_2'];
ci()->db
->set('display_order', $display_order_1)
->where('id', $id_2)
->update($table);
ci()->db
->set('display_order', $display_order_2)
->where('id', $id_1)
->update($table);
}
}
}
You would need to adapt this code, ci() means get_instance(). Also, when you create a new item assign an initial value for its 'display_order' field, for example:
Code:
// Rewrite this using the pure CodeIgniter's query builder.
$this->products->update($id, array('display_order' =>
(int) $this->products
->select('MAX(display_order)')
->with_deleted()
->as_value()
->first()
+ 10
));
Possible extras you could think about:
1. After "Move Up" and "Move Down" update the table using AJAX. Reloading the whole page is quite annoying.
2. Adding a button for drag and drop sorting also would be nice (AJAX), but this is harder.