Skip to main content

Insert Data in DB using ServerResource URL

Step 1. For Creating Liferay MVC and Insert Data in DB using Hibernate Read This

Step 2. Modify createOffer.jsp Page

Know we will send data in controller using Resource URL <portlet:resourceURL var="addNewOfferURL"/> not by Action URL

Copy this code

<%@ include file="/html/init.jsp" %>

<portlet:actionURL var="cancelCreateOfferURL" name="cancelCreateOffer"/>


<portlet:resourceURL var="addNewOfferURL"/>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.validate.min.js" charset="utf-8"></script>

<script>
    var gResourceURL = "<%= addNewOfferURL%>";
   
    function makeAJAXCall(url, ajaxParms, async) {
        console.log("home.jsp makeAJAXCall called with url=" + url + " and ajaxParms=" + JSON.stringify(ajaxParms) + " and async=" + async);

        if (undefined == async || "undefined"  == typeof async || null == async ) {
            async = true;
        }

        var currentAjaxRequest = $.ajax({
            url:url,
            dataType: "json",
            data: ajaxParms,
            type : "post",
            async : async,
            success : function(data) {
                                console.log("addNewOfferURL makeAJAXCall: success received data=" + JSON.stringify(data));
                              
                                },

            error : function(jqXHR, textStatus, errorThrown) {
                                console.log("addNewOfferURL makeAJAXCall: ERROR event with textStatus=" + textStatus + ", errorThrown=" + errorThrown + " and jqXHR="+JSON.stringify(jqXHR));
                               
                              
                    }
        });
    }
    function printJSON(div, jsonResult) {
        console.log("printJSON called with div=" + div + " and jsonResult=" + JSON.stringify(jsonResult));
    }
   
    function submitBtn(){
       //makeAJAXCall(gResourceURL, "methodName=addNewOfferURL&"+$('#addNewForm').serialize());
    }
   
    //makeAJAXCall(gResourceURL, {methodName:'findOffer', status: 'active', keyword:'mountaindew'});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>

<!-- CreateOffer Form start here -->
<form method="post" id="myForm" name="myForm" action="${addNewOfferURL}">
    <fieldset>
                <div class="fieldgroup">
            <label for="offerTitle"><liferay-ui:message key="offerTitle"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="offerTitle" id="offerTitle" />
        </div>

                <div class="fieldgroup">
            <label for="offerCode"><liferay-ui:message key="offerCode"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="offerCode" id="offerCode" />
        </div>
                <div class="fieldgroup">
            <label for="vendor"><liferay-ui:message key="vendor"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="vendor" id="vendor" />
        </div>
                <div class="fieldgroup">
            <label for="areaofDisplay"><liferay-ui:message key="areaofDisplay"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="areaofDisplay" id="areaofDisplay" />
        </div>
                <div class="fieldgroup">
            <label for="desc"><liferay-ui:message key="desc"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="desc" id="desc" />
        </div>
                <div class="fieldgroup">
            <label for="terms"><liferay-ui:message key="terms"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="terms" id="terms" />
        </div>
                <div class="fieldgroup">
            <label for="budget"><liferay-ui:message key="budget"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="budget" id="budget" />
        </div>
                <div class="fieldgroup">
            <label for="budgetType"><liferay-ui:message key="budgetType"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="budgetType" id="budgetType" />
        </div>
                <div class="fieldgroup">
            <label for="startDate"><liferay-ui:message key="startDate"/><em></em></label>
            <input tabindex="2" size="50" type="text" name="startDate" id="startDate" />
        </div>
                <div class="fieldgroup">
            <label for="endDate"><liferay-ui:message key="endDate"/><em></em></label>
            <input tabindex="2" size="50" type="text" name="endDate" id="endDate" />
        </div>
                <div class="fieldgroup">
            <label for="discount"><liferay-ui:message key="discount"/><em></em></label>
            <input tabindex="2" size="50" type="text" name="discount" id="discount" />
        </div>
                <div class="fieldgroup">
            <label for="discountType"><liferay-ui:message key="discountType"/><em></em></label>
            <input tabindex="2" size="50" type="text" name="discountType" id="discountType" />
        </div>
                </div>
                <div class="fieldgroup">
            <label for="limit"><liferay-ui:message key="limit"/><em></em></label>
            <input tabindex="2" size="50" type="text" name="limit" id="limit" />
        </div>
                </div>
                <div class="fieldgroup">
            <label for="upc"><liferay-ui:message key="upc"/><em>*</em></label>
            <input tabindex="2" size="50" type="text" name="upc" id="upc" />
        </div>
       
       
    </fieldset>
    <div class="buttonrow">
        <input tabindex="10" type="button" class="btn" value="Save" onclick="submitForm();" />
        <input tabindex="11" type="button" class="btn" value="Cancel" onclick="cancelAddNewCompany()"/>
    </div>
    <textarea id="offerResponseJSON" name="offerResponseJSON" style="visibility:hidden;"></textarea>
</form>
<!-- Offer Portlet Form end here -->

<script>

function submitForm() {
    //$("#name_error_message").remove();
    var validator = $("#myForm").validate({
        rules : {                           
            offerCode : {required : true, maxlength : 25 },
            offerTitle : {required : true, maxlength : 25 },
            upc : {required : true, maxlength : 80 },
            vendor : {maxlength : 25},
            areaofDisplay : {maxlength : 25},
            desc : {maxlength : 25},
            terms : {maxlength : 25},
            budget : {maxlength : 25},
            budgetType : {maxlength : 25}           
        },           
        messages : {
            offerCode : { required : "<liferay-ui:message key='offerCode-required'/>",
                     maxlength : "<liferay-ui:message key='offerCode-maxlength'/>" },
            offerTitle : { required : "<liferay-ui:message key='offerTitle-required'/>",
                         maxlength : "<liferay-ui:message key='offerTitle-maxlength'/>" },
            upc : { required : "<liferay-ui:message key='upc-required'/>",
                             maxlength : "<liferay-ui:message key='upc-maxlength'/>" },
                           
            vendor : {maxlength :"<liferay-ui:message key='vendor-maxlength'/>"},
            areaofDisplay : {maxlength :"<liferay-ui:message key='areaofDisplay-maxlength'/>"},
            desc : {maxlength :"<liferay-ui:message key='desc-maxlength'/>"},
            terms : {maxlength :"<liferay-ui:message key='terms-maxlength'/>"},
            budget : {maxlength :"<liferay-ui:message key='budget-maxlength'/>"},
            budgetType : {maxlength :"<liferay-ui:message key='budgetType-maxlength'/>"},
           
           
           
        }
    });

    if(validator.form()) {
        console.log("Validate");
        var offer = {
                offerCode : $("#offerCode").val(),
                offerTitle : $("#offerTitle").val(),
                vendor : $("#vendor").val(),
                areaofDisplay : $("#areaofDisplay").val(),
                desc : $("#desc").val(),
                terms : $("#terms").val(),
                budget : $("#budget").val(),
                budgetType : $("#budgetType").val(),
                startDate : $("#startDate").val(),
                endDate : $("#endDate").val(),
                discount : $("#discount").val(),
                discountType : $("#discountType").val(),
                limit : $("#limit").val(),
                upc : $("#upc").val()
            } ;
            $("#offerResponseJSON").val(JSON.stringify(offer));
           
            makeAJAXCall(gResourceURL, {methodName:"addNewOfferURL",offerResponseJSON:JSON.stringify(offer)});
           
            //$('form#myForm').submit();
        }
    }

function cancelAddNewCompany() {
    window.location.replace("<%= cancelCreateOfferURL%>");
    }

</script>




Step 3-: Update Code for Controller

Now once user click on Create Offer on view.jsp Controller process action gets the input (method name)  and it passes same to doView where we have wrote logic for taking input and forwarding it to respective jsp(createOffer.jsp)

In serveResource we get ResourceURL "addNewOfferURL"
In ServeResource add these line

    @Override
    public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException{
       
         log.info("serveResource called with ResourceRequest="+resourceRequest );
       
         String methodName = resourceRequest.getParameter("methodName");
       
         log.info("serveResource for OfferPortlet called with methodName="+ methodName);
            if (null == methodName) {
                String msg = "No methodName parameter passed to OffermanagementPortlet.serveResource!";
                NullPointerException e = new NullPointerException(msg);
                log.error(msg,e);
                throw e;
            }
            Gson gson = new Gson();
            HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(resourceResponse);
            PrintWriter writer = httpServletResponse.getWriter();
            resourceResponse.setContentType("text/html");
           
            if(methodName.equalsIgnoreCase("addNewOfferURL")){
                log.info("serveResource.addNewOfferURL called");               
               
             try {
                int offerId = (int)CounterLocalServiceUtil.increment();
                String responseData = resourceRequest.getParameter("offerResponseJSON");
               
                Gson gson2 = new Gson();
                JsonReader reader = new JsonReader(new StringReader(responseData));
                Offer offer = gson2.fromJson(reader, Offer.class);
                offer.setOfferId(offerId);
                reader.setLenient(true);
                log.info("------Entered in Save New offer Offer DAO Called ----");
                OfferDAO offerDAO = OfferFactory.create();
               
                int returnOfferId = offerDAO.addOffer(offer);
               
               
            } catch (SystemException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
               
                String status = resourceRequest.getParameter("status");
                ArrayList<Offer> offersJSON = getListOffer(status);
                writer.write(gson.toJson(offersJSON));
                log.info("serveResource. called"+gson.toJson(offersJSON));

            }
           
            super.serveResource(resourceRequest, resourceResponse);
    }


Rest Code will be same as my previous one http://liferayvishal.blogspot.in/2015/06/insert-datawithout-using-service.html

Comments

Popular posts from this blog

Liferay 7.1 Topics Coming Soon stay connected

1. Liferay 7.1 Service Builder 2. Rest Service and Liferay 3. Consuming SOAP service with Liferay 7.1 4. Creating Theme With Liferay 7.1 Using Liferay IDE Using NPM 5. Create Angular NPM Module 6. Web Content Management 7. OSGI Basic 8. Liferay 7.1 with more than 1 DB 9. A sample project 10. Liferay Dev Ops

How the portal page is loaded with respective portlets

How the portal page is loaded with respective portlets When a user requests a page with a URL, 1.    The browser sends the request to the Application Server (AS). 2.    Liferay gets the page name from the URL. 3.    It goes to the layout database table and finds the related        theme and page layout. 4.    Based on the page layout, Liferay finds the portlets added        into each area of the page layout. 5.    Liferay runs the portlet and adds the output in the        portlet.vm template. 6.    Liferay interprets the portlet.vm template and adds the output        in the page layout. 7.    Then Liferay interprets the page layout and adds the output in        the portal_normal.vm template. 8.    After that Liferay interprets the portal...

Liferay Custom Field and Custom Attribute (Using Liferay UI and Programatically)

Custom fields are a way to add attributes to many types of assets in the portal. Its basically help us to add additional fields to existed models or entities. Adding some more additional attributes to existed entities or models helps us so to meet our requirements. Liferay provide two way's to allow the creation of Custom Fields. 1. Using Liferay UI 2. Programatically Lets look these both topic one by one-: Suppose you have a scenario where its needed to add few fields in your User_ Table So its simple to add using Liferay UI just you need to follow these steps-: 1. Using Liferay UI-:   Goto-> Control-Panel -> Click on Custom Field A List will be displayed-: Now you can add your custom fields for any entity in the list. Click on User Entity and a page will be displayed like this-: Now add these value in respective fields-: KEY- myContactId Type- Select Integer After adding the custom field we can view, update from the Lifera...