Фев 192012
 

Использование MooTools 1.2 для Drag, Drop, Sort, Save с примером

Мои клиенты любят контролировать содержимое своего сайта, поэтому я создаю функционал для этого. Для лучшего удобства администрирования я использую функции Drag and Drop Menu, с возможностью записи в базу данных. Данная функция помогает сортировать список. Это очень удобно и экономит время, так как не требуется перегружать полностью страницу.

Вот один из способов реализовать данную функцию с помощью JavaScript библиотеки MooTools.

The MySQL Table

id title sort_order
1 Article 1 1
2 Article 2 2
3 Article 3 3
4 Article 4 4
5 Article 5 5
6 Article 6 6

 

The PHP / XHTML

<?php
<div id="message-box"><?php echo $message; ?> Waiting for sortation submission...</div>

<form id="dd-form" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<p><input type="checkbox" value="1" name="auto_submit" id="auto_submit" <?php if($_POST['auto_submit']) { echo 'checked="checked"'; } ?> /> <label for="auto_submit">Automatically submit on drop event</label></p>

<ul id="sortable-list">
  <?php 
    $sort_order = array();
    while($item = mysql_fetch_assoc($result))
    {
      echo '<li class="sortme" alt="',$item['id'],'">',$item['title'],'</li>';
      $sort_order[] = $item['sort_order'];
    }
  ?>
</ul>
<br />
<input type="hidden" name="sort_order" id="sort_order" value="<?php echo implode($sort_order,'|'); ?>" />
<input type="submit" name="do_submit" value="Submit Sortation" class="button" />
</form>
<?php } else { ?>

  <p>Sorry!  There are no items in the system.</p>

<?php } ?>

 

The CSS

#sortable-list {
padding:0;
}
li.sortme {
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;
}

 

The MooTools JavaScript

/* when the DOM is ready */
/* create sortables */
  var sb = new Sortables('sortable-list', {
    /* set options */
    clone:true,
    revert: true,
    /* initialization stuff here */
    initialize: function() { 

    },
    /* once an item is selected */
    onStart: function(el) { 
      el.setStyle('background','#add8e6');
    },
    /* when a drag is complete */
    onComplete: function(el) {
      el.setStyle('background','#ddd');
      //build a string of the order
      var sort_order = '';
      $$('#sortable-list li').each(function(li) { sort_order = sort_order +  li.get('alt')  + '|'; });
      $('sort_order').value = sort_order;

      //autosubmit if the checkbox says to
      if($('auto_submit').checked) {
        //do an ajax request
        var req = new Request({
          url:'<!--?php echo $_SERVER['PHP_SELF']; ?-->',
          method:'post',
          autoCancel:true,
          data:'sort_order=' + sort_order + '&ajax=' + $('auto_submit').checked + '&do_submit=1&byajax=1',
          onRequest: function() {
            $('message-box').set('text','Updating the sort order in the database.');
          },
          onSuccess: function() {
            $('message-box').set('text','Database has been updated.');
          }
        }).send();
      }
    }
  });
});

 

The «Header» PHP / MySQL

/* on form submission */
if(isset($_POST['do_submit'])) 
{
  /* split the value of the sortation */
  $ids = explode('|',$_POST['sort_order']);

  /* run the update query for each id */
  foreach($ids as $index=>$id)
  {
    if($id != '')
    {
      $query = 'UPDATE test_table SET sort_order = '.$index.' WHERE id = '.$id;
      $result = mysql_query($query,$connection) or die(mysql_error().': '.$query);
    }
  }

  /* now what? */
  if($_POST['byajax']) { die(); } else { $message = 'Sortation has been saved.'; }
}

Я считаю, что на сегодняшний день такой способ сортировки является самым быстрым, и современным.

Переведено из источника:
http://davidwalsh.name/mootools-drag-drop