Friday, 18 May 2012

service builder with crud operation in liferay



  Crud and Search opration in Liferay:
 
   ->  Liferay use service builder techniq for Crud opration.
   ->  Service builder purform by  Service.xml file.
   ->  Service.xml file create table in database and also create class and diffrent method.
 
1)     Create service.xml file.
            ->Create service.xml file in WEB-INF and write below code.
            ->CODE:

       <service-builder package-path="com.test">  

      <namespace>qr</namespace> 

        <entity name="Searchclass" local-service="true"
                                       remote- service="false">  
          
            <column name="id" type="long" primary="true"/>    
             <column name="itemname" type="String" />      

            <finder name="Itemname" return-type="Collection"
               <finder-column name="itemname" />
            </finder>
       </entity>

   </service-builder>     


          #1Java package for code

          #2 Namespace for tables

          #3 Name of entity

          #4 Primary key

          #5 Additional fields

          #6 Finder methods

    
   ->Then after build service using cmd:
        ant build-service
   ->Then after compile process use cmd:
        ant compile
   -> Then deploy project:
        ant deploy

   -> In eclips use ant tool and click build-service tag.
        ->Then after refresh  project and click compile tag.
        ->Once again refresh project and deploy .
  



      ->When ant build-service run after that refresh project then see new folder and some new java file  is  created.
       ->Files and folder are define below image:


    ->In above two  image define two folder firsst one has service and second one has src which has  com/test/model , com/test/service folder . This all are created by ant build-service command.
     
    -> com/test/model/service/impl has file SearchclassLocalServiceImpm.java in which we create
      any method and use as service builder class  method.

   -> Create method and ant build-service,ant compile and refresh project. After that see created method in   file WEB-INF/service/com/test/service/SearchclassLocalserviceUtil.java  use for requiered purpos. 
   
    -> Use <finder> in service.xml and ant build-service,ant compile,the finder maethod is genrated in /WEB-INF/service/com/test/service/persistence/SearchclassPersistence.java .     



2)     How to add data in table:
     
       2.1)create .jsp page which display UI tag.
              ->Write code below :
  
 
      <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
       <%@ taglib uri="http://alloy.liferay.com/tld/aui" prefix="aui" %>
      <%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
     
<portlet:defineObjects />

<portlet:actionURL name="Add" var="add" />

<aui:form name="a" action="<%=add.toString() %>" method="post" >

 <aui:input type="text" label="Name" name="nm" value="" />
 <aui:button type="submit" value="Save" />

</aui:form> 
           
    2.2) Make code for insert in /docroot/WEB-INF/src/com/test/NewPortlet.java
           ->Write below code :
  package com.test;

  import javax.portlet.ActionRequest;
  import javax.portlet.ActionResponse;
  import com.liferay.counter.service.CounterLocalServiceUtil;
  import com.liferay.util.bridges.mvc.MVCPortlet;
  import com.test.model.Searchclass;
  import com.test.model.impl.SearchclassImpl;
  import com.test.service.SearchclassLocalServiceUtil;

  public class NewPortlet extends MVCPortlet {
         public void Add(ActionRequest ar , ActionResponse aq) throws Exception
                {
                               String str=ar.getParameter("nm");
              
     //Auto increament primary key.  
        long l=  CounterLocalServiceUtil.increment(Searchclass.class.getName());
                                    
     // Service.xml create class which instance declare usinf *Imlp()

                      Searchclass ins=new SearchclassImpl();
                    
                      ins.setId(l);
                   
                      ins.setItemname(str);

       // Add entry in table
                     SearchclassLocalServiceUtil.addSearchclass(ins);

                  }
           }

       ->In above code has “Add” method which is define in <portlet:actionURL name="Add" var="add" /> in .jsp page.

    -> <portlet:actionURL> find “Add” method in Action file and execute it.

3)     Update,delete and Display Entry

     -> Use Search container for Display data and also use Delete and Update
        data.
    
     -> Search container code for Display data and Button for delete and update.
     -> Write Code in Jsp Page:
        
          Code:    

 <liferay-ui:search-container delta="5" emptyResultsMessage="no-users-were-found">
               <liferay-ui:search-container-results>
               <%
               List<Searchclass> tempResults = SearchclassLocalServiceUtil.getSearchclasses(0,SearchclassLocalServiceUtil.getSearchclassesCount());
               results = ListUtil.subList(tempResults, searchContainer.getStart(),    searchContainer.getEnd());
               total = tempResults.size();
               pageContext.setAttribute("results", results);
               pageContext.setAttribute("total", total);
              
               %>
               </liferay-ui:search-container-results>   
                  
               <liferay-ui:search-container-row className="com.test.model.Searchclass" keyProperty="id" modelVar="item">

   //This tag dispaly table data
                
                               <liferay-ui:search-container-column-text name="itemname" value="<%=item.getItemname() %>"/>
  
      //This tag display Buttton Which is assign Jsp page.
                               
                               <liferay-ui:search-container-column-jsp  path="/html/newportlet/button.jsp" align="right"/>
                             
                             
                               </liferay-ui:search-container-row>

                 <liferay-ui:search-iterator />

     </liferay-ui:search-container>

       
   ->For button in search container, first create jsp page for button and also
     Create method for button event like update,delete otherwise it genrate 
     Error. Let see code below.

   ->For button create jsp page which assing in service builder
        <liferay-ui:search-container-column-jsp          path="/html/newportlet/button.jsp" align="right"/>   

   


  ->button.jsp page code:
 
   <%
 ResultRow rslt=(ResultRow)request.getAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
 Searchclass img=(Searchclass)rslt.getObject();
 String prk=String.valueOf(img.getPrimaryKey());
%>

//Button menu tag
<liferay-ui:icon-menu>

  //Create “editProduct” method in Action file for Redirect update form page
        <portlet:actionURL name="editProduct" var="editURL">
       <portlet:param name="key" value="<%=prk%>" />
       </portlet:actionURL>

  // ”EDIT” button for Update event. 
       <liferay-ui:icon image="edit" message="Edit" url="<%=editURL.toString() %>" /> 
 
 // Create “deleteProduct” method in Action file for DELETE
          <portlet:actionURL name="deleteProduct" var="deleteURL">
          <portlet:param name="key" value="<%= prk %>" />
          </portlet:actionURL>

  //”DELETE” Button for DELETE Event
         <liferay-ui:icon-delete url="<%=deleteURL.toString() %>" />
      
</liferay-ui:icon-menu>


   ->After this create method  in Action file which define in code.
         1> editProduct
         2> deleteProduct

    ->Code for Event:

  3.1>For Update code:
   public void editProduct(ActionRequest ar,ActionResponse ap) throws Exception
     {
                String str= ar.getParameter("key");
                long l=Long.valueOf(str);
                                            
       //Retriev table data using Primary key
                
       Searchclass a=SearchclassLocalServiceUtil.getSearchclass(l);
                                            
       //Set Attribute which has all values of specified pk.
                ar.setAttribute("edit",a );
     
      // Redirect to Jsp page which has Update form. 
                ap.setRenderParameter("jspPage","/html/newportlet/edit.jsp");
                                            
      }

     -> Now Create Jsp page which is Update form.Here is edit.jsp Page

   



     -> code fro edit.jsp page:

 //get attribute for update which is fetch in Action file above.1

  <jsp:useBean id="edit" type="com.test.model.Searchclass" scope="request" /> 
 
 
  //Create “updateProductURL” method for Update.
  //”updateProductURL” is custmize method name.give any name. 
    <portlet:actionURL name="updateProductURL" var="updateProductURL"/>
   
   
   <aui:form  action="<%=updateProductURL.toString() %>" method="post"> 

     <aui:input name= "key" value="<%=edit.getPrimaryKey() %>" type="hidden" /> 
 
     <aui:input name="nm" label="name" value="<%=edit.getItemname() %>" size="45" />
    
     <aui:button type="submit" value="Save"/>
  
   
</aui:form> 
  
 
     -> “updateProductURL” method in Action File
  

public void updateProductURL(ActionRequest ar,ActionResponse ap)throws Exception
  {
     String str=ar.getParameter("nm");
     String str1=ar.getParameter("key");
     long l=Long.valueOf(str1);
 
     //Fetch data from table using pk
     Searchclass itm=SearchclassLocalServiceUtil.getSearchclass(l);
 
     //set update data
     itm.setItemname(str);

    // Update method with change data
     SearchclassLocalServiceUtil.updateSearchclass(itm);

        //Redirect to Search container with update entry
     ap.setRenderParameter("jspPage","/html/newportlet/view.jsp");
 }


  3.2>Delete code:
  
   ->Once create button for delete in jsp page then after create delete method
     in Action file.
   
   ->”deleteProduct” is method which is define in jsp page
        <portlet:ActionUrl var=” ” name=” deleteProduct”>
 
    ->Code is below.





  public void deleteProduct(ActionRequest ar,ActionResponse ap) throws Exception
    {
               String str= ar.getParameter("key");
               long l=Long.valueOf(str);
               SearchclassLocalServiceUtil.deleteSearchclass(l);
               ap.setRenderParameter("jspPage","/html/newportlet/view.jsp");
    }
              
                
 4)Search data.
  
  ->We can search data with all column entry Like Primary key,Name,item so on.

  ->In this example use itenname for searching data.

   ->First define finder in service.xml
   
   ->code :                                           

 
   <finder name="Itemname" return-type="Collection">
       <finder-column name="itemname" />
   </finder>
   
   ->Write This code in above </entity>

      1) <finder name="Itemname" return-type="Collection">

    ->name="Itemname" :-> is Finder method name which is genrated by
            ant sercive-build and ant compile time.

     ->Method called by persistence interface and called “Itemname” by         “findbyItemname”       

     ->return-type="Collection" :-> It is return List.

        2)<finder-column name="itemname" />
       
      ->It is define column name which use for search data by this column entry
 
   ->Now to make jsp page to display search form.

        1) Jsp page search.
         Code:

          // Assing ”search” method which is create in  Action file
 
             <portlet:actionURL var="asd"  name ="search" />

          // Search form
             <aui:form name="b" action="<%=asd.toString() %>" method="post" >
               <aui:input type="text" label="Name" name="nm" value="" />
               <aui:button type="submit" value="Search" />
             </aui:form>

      








       2)In Action file
         
         ->Create method which name is “search”
         ->Code :
           
   public void search(ActionRequest req,ActionResponse res) throws Exception
                {
                                              
                   String str = req.getParameter("nm");
                             
        //Set attributes for search result
                   req.setAttribute("nma",str);
     
        //Redirect search container to display result                   
                   res.setRenderParameter("jspPage","/html/newportlet/view.jsp");
                                                                                           
                }           
                 
          ->This code only redirect to search result jsp page with required attributes.

         ->Now we use *Impl.java file and also *persistence interface.

         ->In *Impl.java create custom method and use *persistence interface in  method for search data.

          -> Action file called customize method which is created in *Impl.java
and *Impl method called finder method by *persistence interface.

         ->Below code specified it. We display result in search container.

       1)Create search container in jsp page
          ->Code:

<liferay-ui:search-container delta="5" emptyResultsMessage="no-users-were-found" >
<liferay-ui:search-container-results

 //Call *impl customize method usin *LocalServiceUtil class
 // Method name is “searchbyuser”

  results="<%= SearchclassLocalServiceUtil.searchbyuser(str) %>"

//size of result
  total="<%= SearchclassLocalServiceUtil.searchbyuser(str).size()%>"         
               />
              
 //Create Instance of service builder class
                  
               <liferay-ui:search-container-row className="com.test.model.Searchclass" keyProperty="id" modelVar="itename">
              
 //Display Result               
                                            
                              <liferay-ui:search-container-column-text name="itemname" value="<%=itemname.getItemname() %>"/>
                               </liferay-ui:search-container-row>

                 <liferay-ui:search-iterator />

     </liferay-ui:search-container>

  -> Now let see how *Impl class work.
 
     1) Create method in *Impl.java file .
     
    ->  Code :

 public  List<Searchclass>  searchbyuser(String name) throws SystemException,PortalException
                {
                             
 // searchPersistence.findByItemname(name) method created by <finder> tag write in servicr.xml file.

 //Return search result in List<>
                    List<Searchclass> a= searchclassPersistence.findByItemname(name);
                               
          return a;
                
        }
              
      ->After that ant build-service and ant compile.

      ->This method is use by *LocalerviceUtil class.