WpDoe
WpDoe

Reputation: 474

CakePHP 3.x update records with jQueryUI Sortable

In one of the views I have implemented a list that can be reordered by drag and drop with jQueryUI Sortable.

The output of the list in meetings.ctp looks like following:

<ul id="sortable">
    <?php foreach($meetings as $meeting): ?>
    <li class="ui-state-default">>
      <?php echo  $meeting['name'] . ' ' . $meeting[place]; ?>
    </li>
    <?php endforeach; ?>
</ul>

The list of meetings is provided based on priority:

$upcommingMeetings_query = $this->MeetingsTasks->find('all')
    ->order(['Meetings.priority' => 'ASC']);

What I need to get done is to update the priority of a Meeting record once it it has been moved. However, I can only find example for how to do this in older versions of CakePHP using JsHelper which is no longer available.

Any help or guidance is much appreciated. If there is any code that I should have shared, please ask for it.

Upvotes: 1

Views: 572

Answers (1)

valar morghulis
valar morghulis

Reputation: 2017

First of all remove extra > from line <li class="ui-state-default">> and then use the stop event of sortable

$( "#selector" ).sortable({
  stop: function( event, ui ) {
    //Invoke the serialize method:
    var sorted = $(this).sortable('serialize');
    console.log(sorted);
    //output: 'sort[]=4&sort[]=1&sort[]=2&sort[]=5&sort[]=3'
    //here goes your ajax request to server
    $.ajax({
       url: 'someURL',
       cache: false,
       type: 'post',
       data: sorted,
       success: function(result) {//parse it here}
    });
  }
});

Your .ctp code should be something like this:

<ul id="sortable">
    <?php foreach($meetings as $meeting): ?>
        <li class="ui-state-default" id="sort-<?php echo $meeting['id']; ?>">
           <?php echo  $meeting['name'] . ' ' . $meeting['place']; ?>
        </li>
    <?php endforeach; ?>
</ul>

You can customize <li class="ui-state-default" id="sort-<?php echo $meeting['id']; ?>"> this part by replacing sort with anyhing you want.

On controller part you will have to parse it in foreach loop and update your db accordingly, or you may save as it is. working link

Upvotes: 2

Related Questions