ColdFusion ORM + jQuery Sortable example
Tonight I decided to throw together a cool example that uses jQuery sortable and ColdFusion 9 ORM. I like to provide an easy way to sort shorter lists. Obviously if you have a list with a lot of elements you won't do this but for shorter lists it works out great. In this example I have a small CMS where pages have a sort order. I want the user to be able use a UI and change the sort order.
First off we need to enable ORM and set our data source. If you want to follow along at home just setup a data source named sortabledemo. Next I am going to setup my Page model. And Finally I am going to setup a page service component. This service will be used as an api for working with pages. The first method will be list which uses the entity save method to retrieve a list of pages from the database and sort them by sort order.
Now I am going to create a page that will show the list of pages. Its important to note that for the sortable component to work you need to used the format name_id for the id of the element that is sortable. Next we need to write some javascript. First we are creating our sortable list. Next we are using a built in method of the sortable api serialize to get the order of our elements. Finally we are making a call to our update sort order method.
Finally to make all this work we need to write some code that will update the database. This is the really cool part because with ORM it is super easy to do. Basically a list comes over that looks like this "page[]=3&page[]=2&page[]=1&page[]=5&page[]=4". We can loop over that list and during each loop we can update the database. Because the index starts at 1 we can set the sort order to the order of the loop every time and use the id as the page we are updating.
