Brian McKeiver's Blog

Build A Content Slider With The Kentico CMS REST Service–Part 2


Recap

This is the second part of my two part blog post mini series on a real world example intended to talk trhough buidling a very typical home page element, the venerable content slider. Please make sure to read the first post of the series if you have not yet.

 

Down to Business

Now that we are sure our REST Service is working. Let’s setup the example. Create a page in your site named Content Slider or Image Slider or re-use the Home page that you probably already have. Next lets add some images as Attachments to the page. Basically we are going to use the page as the container for the content slider, and the attachements will be the content of each slide in the slider. There are many different we could setup this data, but this might be the most simple setup to get the concept across. At the end you should have something that looks like this.
 

Kentico Document Properties
Kentico Document Attachments


Alright now that our container and source data is all set, lets make some REST calls. Head on back over to the REST Testing Interface Module via CMSDesk –> Tools. Our first step is to create an Object Method that returns us information about the images that are attachments in the system. To do so we need to know which Object type we are dealing with, in our case CMS.Attachment, and which DocumentID the attachments are associated to. If you look close on the first screen shot above of the General Properties you will notice that it specifies that the DocumentID we need is 72. Now we can create our REST query and test it in the Testing Interface.

If you follow the documentation on constructing REST queries for Objects, you can probably guess our base query.
 

~/rest/?format=&where=


After filling in our variables it translates to:
 

~/rest/cms.attachment?format=json&where=AttachmentDocumentID=72


Now we can place the above querystring into the REST Testing Interface and see that we get the data we are looking for. The filter correctly returns only the attachments that we want for the specificed document.
 

REST Testing Inteface


By default you can see that the REST Response contains quite a bit of information. To slim it down a bit you can specify which fields, via the columns parameter, you would like to return instead of every single field available. Or conversely you can get more information about an Object if you want, like the actual binary data of the file itself via the binary parameter. For this example we really only need the AtttachmentGUID to pass to the GetAttachment handler to get our images. The final call will look like this:
 

REST Testing Interface with Filter


Now that we have a way to get the correct AttachmentGUID, we can easily construct a URL that should resolve correctly to the image by appending the AttachmentGUID to make the following src attribute value:
 


After playing around with the parameters in your REST calls with this UI I hope you agree that is is extremely easy to use. I think it is.
 

JQuery Black Magic Time

Now we need some script to call our REST Service. The following code example can be used to make an asynchronous call back to the service. Using jQuery and it's $.ajax functionality makes this very easy to do. Sometimes it's almost too easy, and that is why I call it Black Magic. Place this code in editable zone on your page.


<script type="text/javascript">
$(function() {
    var params = { 'format': 'json', 'where': 'AttachmentDocumentID=72', 'columns': 'AttachmentGUID'};
    $.ajax({
          type: 'GET',
          url: '/rest/cms.attachment',
          dataType: 'json',
          data: params,
          username: 'rest_user',
          password: 'rest123',
          error: function(xhr, ajaxOptions, thrownError) {
                alert("error");
          },
          success: function(response) {
                alert("worked");

     }
  });
});
script>


As you can see it’s fairly standard jQuery $.ajax code. The only real things to point out here are that we have to pass a username and password in the request because we are using Basic Authentication and we have to specify the type of request as a “GET” otherwise we would not be following REST principles. The above sample just proves that from Javascript we can successfully query the REST Service for our data in our Kentico CMS site.
 

Aren’t We Talking About An Content Slider?

Yep your right I did mention that this was going to provide the content for each slider of an Content Slider. So for this example I am going to use the fantastic bxSlider jQuery Plugin. It is an very nice simple but powerful plugin that will give us our slider. After you follow the instructions to setup the plugin, you can modify the above script and add some HTML to generate the images you need.
 

<ul id="slider">
ul>

<script type="text/javascript">
    $(function () {
        var params = { 'format': 'json', 'where': 'AttachmentDocumentID=72', 'columns': 'AttachmentGUID' };
        $.ajax({
            type: 'GET',
            url: '/rest/cms.attachment',
            dataType: 'json',
            data: params,
            username: 'rest_user',
            password: 'rest123',

            error: function (xhr, ajaxOptions, thrownError) {
                alert("error");
            },
            success: function (response) {
                var data = response.cms_attachments[0].CMS_Attachment;

                for (var i = 0; i < data.length; i++) {
                    var d = data[i].AttachmentGUID;
                    $('#slider').append("
  • + d + "\" />
  • "
    ); } $('#slider').bxSlider({ auto: true, autoDelay: 2000, pause: 5500, autoControls: true }); } }); }); script>

     

    The Result

    Kentico CMS Content Slider

    I have also worked up a demo page to show the full example.
     

    Conclusion

    And there we have it. You should now have a working Content Slider that dynamically loads it’s content via the Kentico CMS REST Service from a set of Document Attachments. Pretty cool eh ? One final note about security. This is a demo / walk through on using REST in Kentico. Please do not ever put a username and password in clear text on the client side and be sure to review the security settings for REST access to your site. The Kentico documentation explains what the settings are and how you can lock your service down.

    As always please leave me any feedback or questions you may have in the comments below.