2015-07-21 7 views
29

Sto usando jQuery Plugin Nestable per creare un editor di menu per un sito Web. Ho cercato di ottenere l'articolo ID e Bambini dopo che l'utente ha fatto clic sulle voci di menu e ha modificato la propria posizione.Come ottenere i bambini e l'id in jQuery Plugin Nestable dopo aver trascinato e rilasciato l'elemento e l'aggiornamento nel database?

Edizione: Non so come ottenere ID e figli e aggiornare nel database.

Ecco jQuery Affiancabile plug

<script> 
    $(document).ready(function() { 
     var updateOutput = function (e) { 
      var list = e.length ? e : $(e.target), output = list.data('output'); 
      if (window.JSON) {output.val(window.JSON.stringify(list.nestable('serialize')));//, null, 2)); 
      } else { 
       output.val('JSON browser support required for this demo.'); 
      } 
     console.log(list.nestable('serialize')); 
     console.log(window.JSON.stringify(list.nestable('serialize'))); 
     }; 
     $('#nestable').nestable({ 
      group: 1, 
      maxDepth: 7, 
     }).on('change', updateOutput); 
     updateOutput($('#nestable').data('output', $('#nestable-output'))); 
    }); 
</script> 

Ecco HTML per i menu

<div class="cf nestable-lists"> 
    <div class="dd" id="nestable"> 
     <ol class="dd-list"> 
      <li class="dd-item" data-id="1"> <div class="dd-handle">Item 1 when parent == 0</div> </li> 
      <li class="dd-item" data-id="44"> <div class="dd-handle"> Item 2 when this parent_id == its id </div> 
       <ol class="dd-list"> 
        <li class="dd-item" data-id="3"><div class="dd-handle">Item 3</div></li> 
        <li class="dd-item" data-id="4"><div class="dd-handle">Item 3</div></li> 
        <li class="dd-item" data-id="5"><div class="dd-handle">Item 3</div></li> 
        <li class="dd-item" data-id="6"><div class="dd-handle">Item 3</div></li> 
       </ol> 
      </li> 
     </ol> 
    </div> 
</div> 

Il risultato sul Console

[{"id":1},{"id":44,"children":[{"id":3},{"id":4},{"id":5},{"id":6}]}] 

Edition

Nella mia struttura voglio aggiornare menu quando parent_id==id dove i menu id e creare livello di menu Numero Voce bu del M_order. Ma non so per creare questa struttura.

E qui è var_dump ($ this-> input-> post ('list'));

1 => 
    array (size=1) 
     'id' => string '2' (length=1) 
    2 => 
    array (size=1) 
     'id' => string '3' (length=1) 
    3 => 
    array (size=1) 
     'id' => string '4' (length=1) 
    4 => 
    array (size=1) 
     'id' => string '5' (length=1) 
    5 => 
    array (size=2) 
     'id' => string '6' (length=1) 
     'children' => 
     array (size=1) 
      0 => 
      array (size=2) 
       ... 

Ecco le immagini della mia Tabella struttura e menu

enter image description here

+1

Qual è il tuo attuale file PHP per l'archiviazione/il recupero di questi dati dal database? E qual è la struttura della tabella del database che contiene tali informazioni? E qual è il fornitore di DB, MSSQL, MySQL? –

+0

Non so fare in PHP e anche come trovare Id e bambini e Come posso aggiornare m_order quando l'utente cambia posizione posizione –

+1

Questo requisito rende la tua domanda troppo ampia. Stackoverflow è un sito di domande e risposte, in cui ci si aspetta che tu provi le cose da solo, e quando rimani bloccato, puoi porre domande specifiche. Dai un'occhiata alla pagina di aiuto [Come chiedere] (http://stackoverflow.com/help/how-to-ask). Detto questo, mi è sembrato un po 'divertente, quindi sono andato avanti e ho scritto uno script PHP per salvare l'ordine su ogni cambiamento. Ma è un'implementazione generica, probabilmente dovrai modificarla per farlo funzionare per la tua pagina. Ho modificato la mia risposta per includerla, verificarla. –

risposta

20

Per inviare l'elenco per PHP, è necessario cambiare la vostra funzione updateOutput per pubblicare la lista tramite la tecnologia AJAX:

<script> 
$(document).ready(function() { 
    var updateOutput = function (e) { 
     var list = e.length ? e : $(e.target), output = list.data('output'); 

     $.ajax({ 
      method: "POST", 
      url: "saveList.php", 
      data: { 
       list: list.nestable('serialize') 
      } 
     }).fail(function(jqXHR, textStatus, errorThrown){ 
      alert("Unable to save new list order: " + errorThrown); 
     }); 
    }; 

    $('#nestable').nestable({ 
     group: 1, 
     maxDepth: 7, 
    }).on('change', updateOutput); 
}); 
</script> 

In PHP, riceverai $_POST['list'], che apparirà come mostrato di seguito. In questo caso, ho trascinato il 4 ° punto (id 6) al 2 ° posto (dopo id 3) nella lista, quindi l'ordine previsto è 3, 6, 4, 5:

Array (
    [0] => Array (
     [id] => 1 
    ) 
    [1] => Array (
     [id] => 44 
     [children] => Array (
      [0] => Array (
       [id] => 3 
      ) 
      [1] => Array (
       [id] => 6 
      ) 
      [2] => Array (
       [id] => 4 
      ) 
      [3] => Array (
       [id] => 5 
      ) 
     ) 
    ) 
) 

allora si può solo iterare questo array e aggiornamento il tuo database di conseguenza.


Edit: Al fine di salvare i dati in PHP, dovrete utilizzare la ricorsione per navigare tutte le matrici bambini che potrebbero esistere. Ho scritto un semplice script che salverà su ogni modifica degli ordini:

indice .php

<?php 
require "pdoConnection.php"; 
$list = getFullListFromDB($conn); 
?> 

<html> 
<head> 
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
<script src="https://cdn.rawgit.com/dbushell/Nestable/master/jquery.nestable.js"></script> 
<script> 
$(document).ready(function() { 
    var updateOutput = function (e) { 
     var list = e.length ? e : $(e.target), output = list.data('output'); 

     $.ajax({ 
      method: "POST", 
      url: "saveList.php", 
      data: { 
       list: list.nestable('serialize') 
      } 
     }).fail(function(jqXHR, textStatus, errorThrown){ 
      alert("Unable to save new list order: " + errorThrown); 
     }); 
    }; 

    $('#nestable').nestable({ 
     group: 1, 
     maxDepth: 7, 
    }).on('change', updateOutput); 
}); 
</script> 
</head> 

<body> 
<div class="cf nestable-lists"> 
    <div class="dd" id="nestable"> 
<?php displayList($list); ?> 
    </div> 
</div> 
</body> 
</html> 

<?php 
function getFullListFromDB($conn, $parent_id = 0) { 
    $sql = " 
     SELECT id, parent_id, description 
     FROM items 
     WHERE parent_id = :parent_id 
     ORDER BY m_order 
    "; 

    $statement = $conn->prepare($sql); 
    $statement->bindValue(':parent_id', $parent_id, PDO::PARAM_INT); 
    $statement->execute(); 

    $result = $statement->fetchAll(PDO::FETCH_ASSOC); 

    foreach($result as &$value) { 
     $subresult = getFullListFromDB($conn, $value["id"]); 

     if (count($subresult) > 0) { 
      $value['children'] = $subresult; 
     } 
    } 
    unset($value); 

    return $result; 
} 

function displayList($list) { 
?> 
    <ol class="dd-list"> 
    <?php foreach($list as $item): ?> 
    <li class="dd-item" data-id="<?php echo $item["id"]; ?>"><div class="dd-handle"><?php echo $item["description"]; ?></div> 
    <?php if (array_key_exists("children", $item)): ?> 
    <?php displayList($item["children"]); ?> 
    <?php endif; ?> 
    </li> 
    <?php endforeach; ?> 
    </ol> 
<?php 
} 
?> 

saveList.php

<?php 

require "pdoConnection.php"; 

if ($_POST) { 
    saveList($conn, $_POST['list']); 
    exit; 
} 

function saveList($conn, $list, $parent_id = 0, &$m_order = 0) { 
    foreach($list as $item) { 
     $m_order++; 

     $sql = " 
      UPDATE items 
      SET 
       parent_id = :parent_id, 
       m_order = :m_order 
      WHERE id = :id 
     "; 
     $statement = $conn->prepare($sql); 
     $statement->bindValue(":parent_id", $parent_id, PDO::PARAM_INT); 
     $statement->bindValue(":id", $item["id"], PDO::PARAM_INT); 
     $statement->bindValue(":m_order", $m_order, PDO::PARAM_INT); 
     $statement->execute(); 

     if (array_key_exists("children", $item)) { 
      saveList($conn, $item["children"], $item["id"], $m_order); 
     } 
    } 
} 

?> 

pdoConnection.php

<?php 
$server = "myServer"; $database = "DbName"; $username = "myself"; $password = "secret"; 
$conn = new PDO("sqlsrv:Server=$server;Database=$database", $username, $password); 
?> 

definizione tabella (MSSQL)

CREATE TABLE [items](
    [id] [int] NOT NULL, 
    [parent_id] [int] NOT NULL, 
    [description] [nvarchar](100) NOT NULL, 
    [m_order] [int] NOT NULL, 
    CONSTRAINT [PK_items] PRIMARY KEY CLUSTERED ([id] ASC) 
) ON [PRIMARY] 

INSERT [items] ([id], [parent_id], [description], [m_order]) VALUES (1, 0, N'Item 1', 1) 
INSERT [items] ([id], [parent_id], [description], [m_order]) VALUES (2, 0, N'Item 2', 2) 
INSERT [items] ([id], [parent_id], [description], [m_order]) VALUES (3, 2, N'Item 3.1', 3) 
INSERT [items] ([id], [parent_id], [description], [m_order]) VALUES (4, 2, N'Item 3.2', 4) 
INSERT [items] ([id], [parent_id], [description], [m_order]) VALUES (5, 2, N'Item 3.3', 5) 
INSERT [items] ([id], [parent_id], [description], [m_order]) VALUES (6, 2, N'Item 3.4', 6) 
+0

Sono così difficile aggiornare questo array nel mio database –

+1

Cosa hai provato fino ad ora? Modifica la tua domanda e aggiungi il tuo attuale script PHP e la struttura della tabella. –

+0

Ti ringrazio molto per la tua risposta, lasciami provare ora tornerò quando sarò pronto. Grazie –

Problemi correlati