Multiple Sortable Lists, 1 Update mattward
So I have the pleasure of bringing you our first post. I know the excitement is overwhelming, so I won’t bore you. Here we go, right into it. This post is mainly going to talk about how we can use the Scriptaculous library with a bit more Javascript code to make easy to use (and damn cool looking) sortable lists of data. Sure, the Scriptaculous wiki shows you an example using Ruby on Rails, but I perfer to code in PHP (so does just about everyone here at CollegeHumor). The basic use is quite simple. We have an unordered list (UL element) with a bunch of list items (LI elements). After we include the Scriptaculous (and obviously Prototype) library in our code, we can create a sortable list as quickly as using the code:
Sortable.create('id_of_UL_element',[options]);
This whole function and its options are very well documented on the Scriptaculous wiki, so I am just going to talk about how to create a bunch of lists that you can drag between and how we can send all the data to our database for storage using a single button.
The first step is to make sure that we can drag elements between our lists. This is as simple as setting the options kind of like this:
containable_lists.each(
function (containable_list) {
Sortable.create(containable_list,
{containment:containable_lists,constraint:false,scroll:window});
}
);
The variable containable_lists should be an array of all the lists you want to be able to drag between. This quick little script created all the sortable lists for us quickly and easily.
Now for the second step, a bit more of a challenge, creating the one button that updates it all. When the button is clicked we need to loop through all the containers and use the Sortable.serialize function to prepare them to be sent to our PHP function (you can use an AJAX request with the data or just do a regular POST or GET method with the data). The code to serialize all the data is very similar to the code we used to create the Sortable lists, but rather than creating we will serialize all the data and push it to the end of an array.
var data = new Array();
containable_lists.each(
function (containable_list) {
data.push(Sortable.serialize(containable_list));
}
);
The array data now contains an array of arrays that you can handle in PHP quite easily. If you had two containers with IDs, list_1 and list_2, the array data would be something like:
Array
(
[0] => Array
(
[0] => item_1
[1] => item_2
[2] => item_3
)
[1] => Array
(
[0] => item_4
[1] => item_5
[2] => item_6
)
)
That’s it for now. Check back soon for more posts for some other people, and maybe even me. Here’s a screenshot of the interface I created that uses very similar code and is currently used to manage our about page at CollegeHumor:

—-
Matt Ward
Developer Intern
CollegeHumor.com
Other Work: MWDesigns