2013-06-22 8 views
10

Sto provando a salvare l'ordine di una tabella con l'interfaccia utente jQuery (ordinabile) in un array PHP.jQuery UI che salva l'elenco ordinabile nell'array PHP

L'ho semplificato in modo considerevole ma questa è l'idea di base. Ho una tabella con una lista ordinabile inclusa in essa. La tabella viene generata tramite un PHP foreach che coinvolge l'array multidimensionale incluso in un altro file (config.php).

config.php:

<?php 
$config  = array(
    "mno" => array('item 5'), 
    "abc" => array('item 1'), 
    "ghi" => array('item 3'), 
    "pqr" => array('item 6'), 
    "jkl" => array('item 4'), 
    "vwx" => array('item 8'), 
    "def" => array('item 2'), 
    "stu" => array('item 7'), 
); 
?> 

tavolo (index.html):

<table cellpadding="2" cellspacing="0" align="center" id="mytable"> 
    <tbody> 
<?php 
    $i = 0; 
    include 'config.php'; 
    foreach($config AS $name => $value){ 
     $item = $value[0]; 
     echo ' 
     <tr id="'.$name.'-'.$i++.'"> 
      <td>'.$item.'</td> 
     </tr>'; 
    } 
?> 
</tbody> 
</table> 

script (index.html):

<!-- Add jQuery library --> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> 
<!-- Add jQuery UI library --> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     var fixHelper = function(e, ui) { 
      ui.children().each(function() { 
       $(this).width($(this).width()); 
      }); 
      return ui; 
     }; 

     $("#mytable tbody").sortable({ 
      helper: fixHelper, 
      opacity: 0.5, 
      scroll: false, 
      update: function() { 
       var data = $('#mytable tbody').sortable('serialize'); 
       $.post("edit.php", {'neworder': data}); 
      } 
     }).disableSelection(); 
    }); 
</script> 

L'ordinamento funziona bene, ma non so come salvare il valore NewOrder ($_POST['neworder']) nella matrice ciò che è in config.php.

penso che devo usare le funzioni PHP uasort() (o uksort(), uksort()) con la combinazione di file_put_contents per salvare il nuovo ordine in config.php.

Quindi qualcosa di simile a questo:.

<?php 
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['neworder'])) { 
    /* 
    Here file_put_contents in config.php the new order. So: 
    $config  = array(
     "mno" => array('item 5'), 
     "abc" => array('item 1'), 
     "ghi" => array('item 3'), 
     "pqr" => array('item 6'), 
     "jkl" => array('item 4'), 
     "vwx" => array('item 8'), 
     "def" => array('item 2'), 
     "stu" => array('item 7'), 
    ); 

    Becomes: 
    $config  = array(
     "abc" => array('item 1'), 
     "def" => array('item 2'), 
     "ghi" => array('item 3'), 
     "jkl" => array('item 4'), 
     "mno" => array('item 5'), 
     "pqr" => array('item 6'), 
     "stu" => array('item 7'), 
     "vwx" => array('item 8'), 
    ); 

    After this is send by Jquery UI: 
    neworder:abc[]=1&def[]=6&ghi[]=2&jkl[]=4&mno[]=0&pqr[]=3&stu[]=7&vwx[]=5 

    I've tried this: 
     $filename = 'config.php'; 

     $lines = file($filename , FILE_IGNORE_NEW_LINES); 
     $linenumber = 2; 
     foreach($_POST['neworder'] AS $name => $val){ 
      $phost = $val[0]; 

      $lines[$linenumber] = ' "'.$name.'" => array(\'' . $phost . '\'),'; 
      $linenumber++; 
     } 

     file_put_contents($filename , implode("\n", $lines)); 

    But the '$val' is not send with Jquery only the order. 

    */ 
} 
?> 
+1

Salvare i dati in file php è una cattiva idea. È possibile memorizzarli in un formato json o xml. Se hai bisogno di farlo su una scala più grande/più frequentemente, devi usare un database. – user568109

+0

@GerritHoekstra Ciao, voglio aiutarti e pensare che non sia così difficile, ma voglio sapere perché lo stai facendo in questo modo sbagliato? Posso cambiare qualche parte di esso mentre è diventato migliore? Voglio dire in generale una tabella con due o più colonne che possono essere ordinate con jui e come i suoi tipi o come l'utente fa clic su un pulsante del nuovo ordine di salvataggio? perché non usi il formato JSON o XML per salvare? e un file chiamato JSON_Config_reader.php in streghe legge quel file JSON e crea quella matrice? – ncm

+0

@GerritHoekstra - sai cosa. Potresti semplicemente fare un commento per me dicendo "bel tentativo". – ncm

risposta

1

Si sta andando a voler utilizzare usort con una chiusura (disponibile in PHP 5.3+) per ottenere le chiavi nell'ordine in cui li avete bisogno in

$newOrder = $_POST["neworder"]; 
$config_keys = array_keys($config); 
usort($config_keys, function($a, $b) use($newOrder) { 
     return array_search($a, $newOrder) - array_search($b, $newOrder); 
}); 

Quindi è possibile modificare riscrittura $ config nel nuovo ordine

$newConfig = array(); 

foreach($config_keys as $key){ 
    $newConfig[$key] = $config[$key]; 
} 
$config = $newConfig; 
unset($newConfig); 

Da qui puoi mantenere $ config in qualunque metodo abbia più senso per il tuo caso d'uso. Vorrei consigliare di non usare per creare un file php, però, un approccio migliore potrebbe essere quella di utilizzare

file_put_contents($cacheFile, serialize($config)); 

poi per recuperare

$config = unserialize(file_get_contents($cacheFile)); 
+1

Grazie, lo userò. Funziona con questa modifica in jQuery UI: 'aggiornamento: function() { \t \t \t \t \t \t var a = $ ('# mytable tbody') ordinabili ('toArray');. \t \t \t \t \t \t var newOrdering = []; \t \t \t \t \t \t for (var i = 0; i user1480019

1

Ci sono così tanti fili che copre il problema

  1. jQuery UI Sortable, then write order into a database
  2. save jquery ui-sortable positions to DB
  3. Optimal way to save order of jQueryUI sortable list with Meteor
  4. http://dev.nirmalya.net/articles/javascript/saving-ordering-of-a-sortable-list-using-jquery-ui

io sono sicuro che troverete la risposta c'è.Tutto è di ottenere l'ordine via

$('#mylist').sortable('toArray'); 

salvarlo nel database

e quindi ottenere l'ordine dal database e mostrare correttamente con loop. Dai un'occhiata ai tutorial.

0

$(function() { $("ul.sortable").sortable({ connectWith: '.sortable', update: function(event, ui) { /* var position = $('.sortable').sortable('serialize', { key: 'menu', connected: true });*/ $('div').empty().html($('.sortable').serial()); } }); });

+0

dopo che aggiungono che il codice – waheed

+0

(function ($) {$ .fn.serial = function() {var Array = []; var $ elem = $ (this); $ elem.each (function (i) { var menu = this.id; $ ('li', this) .each (function (e) { array.push (menu + '[' + '+'] = '+ this.id); });} ); ritorno Array.join (' &'); } }) (jQuery); – waheed

+2

Modifica la tua risposta, non inserire il codice nei commenti. –