Saturday, February 14, 2015

Infinite Scroll

How To Use Infinite Scroll On Dynamic Data In Liferay

Version:Liferay 6.2

*In this example JournalArticle table is used for data, you can use any table for getting data.

Steps:

1> Create one custom portlet with named  "scroll" or  "infinite scroll" or anything as per you requirment naming convention

2>Paste below code in portlet jsp page

view.jsp
---------

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui"%>
<portlet:defineObjects />

<script type="text/javascript" src="https://rawgithub.com/asotog/y-commons/master/build/gallery-y-common-infinite-scroll/gallery-y-common-infinite-scroll-min.js"></script>

<div class = "images-infinite-grid-view">
//content will be placed inside this div after getting content from database.
</div>

<script type="text/javascript">
    AUI().use('gallery-y-common-infinite-scroll', 'datatype-xml', 'transition', 'liferay-portlet-url', 'aui-io-request','aui-base', function (A) {

        var PORTLET_ID = 'infinite_WAR_azharportlet';
        var resourceURL = Liferay.PortletURL.createResourceURL();
        resourceURL.setPortletId(PORTLET_ID);
   
        var offset = 5;
        /* js configuration */
        var itemTemplate = '{content}';
                            
       /* infinite scroll instance */
        var infiniteScroll = new A.InfiniteScroll({
           
            requestCustomData: function (callback) {
               
                var data = Liferay.Util.ns("_"+PORTLET_ID+"_", {
                    'start': this.currentOffset - offset,
                    'end': this.currentOffset,
                });
           
                A.io.request(resourceURL.toString(),{
                    method: 'GET',
                    dataType: 'json',
                    data: data,
                    on : {
                        success:  function(){
                            var entries = this.get('responseData');
                            callback(entries);
                       }
                    }
                });  
            },
            container: A.one('div.images-infinite-grid-view'),
            itemTemplate: itemTemplate,
            initialize: true,
            offset: 5,
            itemPreProcessor: function(item) {
               
                return item;
            }
        });
       
        infiniteScroll.on('infinite-scroll:loading', function (e) {
           alert("loading");  
        });
        infiniteScroll.on('infinite-scroll:finished', function (e) {
          
            infiniteScroll.get('container').all('div').transition({
                easing: 'ease-out',
                duration: 1,
                opacity: 1
            });
           
        });
        infiniteScroll.on('infinite-scroll:no-more-results', function (e) {
          
             alert("no more result to show");
             infiniteScroll.get('container').append("No More Content to show..");
           
        });
    });
    </script>

3> Paste below code in portlet controller(java file)

scroll.java
------------

package com.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.portal.kernel.dao.orm.Criterion;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil;
import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.HtmlUtil;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.OrderByComparatorFactory;
import com.liferay.portal.kernel.util.OrderByComparatorFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.journal.model.JournalArticle;
import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class Infinite
 */
public class Infinite extends MVCPortlet {

   
    @Override
    public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {
       
        int start = ParamUtil.getInteger(resourceRequest, "start");
        int end = ParamUtil.getInteger(resourceRequest, "end");
       
        int totalCount = 0;
        List total = null;
        try {
            total = JournalArticleLocalServiceUtil.
                    dynamicQuery(prepareDynamicQuery(false, start, end));
        } catch (SystemException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
       
        if(Validator.isNotNull(total))
            totalCount = GetterUtil.getInteger(total.get(0));
       
       
        if(totalCount < end )
            end = totalCount;
   
        if(start > end)
            start = end;

        ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
       
        JSONArray jsonarray = JSONFactoryUtil.createJSONArray();
       
        try {
            List<JournalArticle> dynamicarticles = JournalArticleLocalServiceUtil.
                    dynamicQuery(prepareDynamicQuery(true, start, end));
       
            for(JournalArticle dynamicarticle:dynamicarticles){
                   
                JSONObject json = JSONFactoryUtil.createJSONObject();
               
                    String content = StringPool.BLANK;
                    try {
                            content = JournalArticleLocalServiceUtil.getArticleContent(dynamicarticle, "", "", themeDisplay.getLanguageId(), themeDisplay);
                            json.put("content", content);
                            jsonarray.put(json);
                       
                    } catch (PortalException e) {
                        e.printStackTrace();
                    }   
            }
            PrintWriter pw = resourceResponse.getWriter();
            pw.write(jsonarray.toString());           
        } catch (SystemException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
    private DynamicQuery prepareDynamicQuery(boolean wantLimit, int start , int end) {
       
        DynamicQuery query = DynamicQueryFactoryUtil.forClass(
                JournalArticle.class, "articleParent",
                PortalClassLoaderUtil.getClassLoader());
       
        DynamicQuery subQuery = DynamicQueryFactoryUtil
                .forClass(JournalArticle.class, "articleSub",
                        PortalClassLoaderUtil.getClassLoader())
                .add(PropertyFactoryUtil.forName("articleId").eqProperty(
                        "articleParent.articleId"))
                .setProjection(ProjectionFactoryUtil.max("id"));
       
        query = query.addOrder(OrderFactoryUtil.desc("modifiedDate"));

        query = query.add(PropertyFactoryUtil.forName("id").eq(subQuery));
       
       
        // below line can be used for getting custom type of article, like in this case custom types are TOPIC And ARTICLE.
        //For testing you can use default article type like General, test etc.
        query.add(RestrictionsFactoryUtil.or(RestrictionsFactoryUtil.eq("type", new String("TOPIC"))
                , RestrictionsFactoryUtil.eq("type", new String("ARTICLE"))));
   
        if (wantLimit) {
            query.setLimit(start, end);
        } else {
            query.setProjection(ProjectionFactoryUtil.rowCount());
        }

        return query;
         }

}
Location: Bengaluru, Karnataka, India

0 comments:

Post a Comment