Tuesday 29 November 2016

Input type only numbers(html5)

<input name="termsAndConditionsArticleId" value="${programDetailsForm.termsAndConditionsArticleId}" type="text"  pattern="^[0-9]*$" placeholder="Enter Digits only" title="Please enter numeric value only"/>


Increment & Decrements Hidden
<style>
input[type=number] {
    -moz-appearance:textfield;
}
</style>

Wednesday 16 November 2016

Using Liferay Services in VM using ServiceLocator

When developing custom themes, we need to use Liferay services in VM. Its quite easy but tricky. So, putting here a simple example-
Write following in init-custom.vm

#set($organizationLocalService = $serviceLocator.findService("com.liferay.portal.
service.OrganizationLocalServiceUtil" )

Now you can use this service as follows:

#set ($org = $organizationLocalService.getOrganization($myPlace.getClassPK($myPlace.getClassPK()))

   

Getting Youtube Video Thumbnail image

<!--  This is for sample test code  -->

  <script type="text/javascript"> function getScreen( url, size ) {
if(url === null){
return "";
}
size = (size === null) ? "big" : size;
var vid;
var results;

results = url.match("[\\?&]v=([^&#]*)");
vid = ( results === null ) ? url : results[1];
if(size == "small"){
return "http://img.youtube.com/vi/"+vid+"/2.jpg"; }
else {
return "http://img.youtube.com/vi/"+vid+"/0.jpg"; }
}
</script>

 <%
  String url = "http://www.youtube.com/watch?v=E88uMNtPjvw";
 %>
<script type="text/javascript">

var imgUrl_small = getScreen("<%=url%>",'small');

 alert("this is image Url :"+imgUrl_small);

document.write('<img src="' + imgUrl_big + '" />');
document.write('<img src="' + imgUrl_small + '" />');

</script>

I hope its usefully for you..

Vm file image src

Explanation: In this we just have a scenario , that how we can display an image using liferay_portal.vm.In this docroot, under docroot dff folder is there placed any image in image folder.
then open the liferay-portal.vm and put this code


                                          $images_folder                                               

                     <img src="$images_folder/image.png">


here $image_folder means _dff/image
image.png is the image that we have to display.


Friday 4 November 2016

Liferay, Reset Admin password.

If you forget or lose your Liferay Admin user and have access to your Liferay Schema / Database, you can execute the below query to reset your password.

Note: You will have to restart the server for the changes to take place.
 

UPDATE 
  user_ 
SET 
  password_ = '1234',
  passwordEncrypted = '0',
  passwordReset = '1',
  status = 0 
WHERE 
  emailaddress = 'test@liferay.com';
 
password_ is the new password that you are setting. You can use this to log in with the Admin credentials.
emailaddress should be the email Address of the Admin User.

jQuery Datepicker project


I had created a simple jQuery datepicker plugin couple of months back, just wanted to share it.

The plugin converts any input box to a 3 drop down date picker. It gets the name of the input element and attaches a Day, Month and Year respectively. You can access the original field to retrieve the date which will, by default, be in the format yyyy/mm/dd.

So, for example, if your input fields name was dob, then, to retrieve the value for the day, you would use dobDay. For the month it would be dobMonth and year with dobYear. For all event handlers, you will need to use the new name that will be generated.

Find the example JSFiddle link below.
JSFiddle - jQuery Datepicker

Datepicker Source File
Complete Source, (jquery.datepicker.js)

Below is the minified JS file for the datepicker. Copy this to a JavaScript file and include it in the page.
Minified file, (jquery.datepicker.min.js)

Supported Parameters:

startDate: JavaScript Date object to restrict the user to a specific Start date.
endDate: JavaScript Date object to restrict the user to a specific End date.
dateFormat: a function takes (day, month, year) as parameters and that returns a string that will be used to fill the hidden input box.


Usage:
HTML
 

<body>
    <input type="text" name="dob" id="dob" />
</body>

Javascript Code
 

$(function () {
    $('#dob').datepicker();

    // Example: Create 'onChange' handlers.
    $('#dobMonth').on('change', function () {
        alert($(this).val());
    });

    // Example: Display the String value on changin the date.
    $('#dobDay, #dobMonth, #dobYear').on('change', function () {
        alert($('#dob').val());
    });
});

Using the "liferay-ui:input-date" tag


Just a simple example to use the liferay-ui:input-date tag in our forms.

1. Firtly we need to import the required tag.
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>

2. If you need to show the default selected date as Today. We need a Calendar object to get these values for our form.
<%
// To set today's date as default for the calendar.
Calendar today = Calendar.getInstance();
%>

3. Now for the actual form. The Liferay UI Date element is created here with the necessary parameters.
<label>
    Date of Birth
    <liferay-ui:input-date name="dobDate" 
        dayValue="<%= today.get(Calendar.DAY_OF_MONTH) %>" dayParam="dobDay"
        monthValue="<%= today.get(Calendar.MONTH) %>" monthParam="dobMonth"
        yearValue="<%= today.get(Calendar.YEAR) %>" yearParam="dobYear" />
</label>
The dayValue, monthValue and yearValue attributes are displayed to the user as soon as the form is loaded.
dayParam, monthParam and yearParam are the attributes representing the data when it is sent to the server side.
I have also set the name attribute which will send the selected date in MM/dd/yyyy format to the server.

4. Now for the server side, to retrieve the data from the user. This is the first way to fetch the data, below I have provided another way to do the same.
// Method 1
// We can fetch the date either by separate Day, Month and Year parameter.
int dobDay = ParamUtil.getInteger(actionRequest, "dobDay");
int dobMonth = ParamUtil.getInteger(actionRequest, "dobMonth");
int dobYear = ParamUtil.getInteger(actionRequest, "dobYear");

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, dobDay);
calendar.set(Calendar.MONTH, dobMonth);
calendar.set(Calendar.YEAR, dobYear);

System.out.println("Method 1: " + calendar.getTime());
In our Portlet class, the dobDay, dobMonth and dobYear will provide the Day, Month and Year respectively. We can set this to a Calendar object and retrieve the Date object with the calendar.getTime() method.

5. Now for method 2.
// Method 2
// With the input String from the selected date.
try {
    String dobDateString = ParamUtil.getString(actionRequest, "dobDate");
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    Date dobDate = sdf.parse(dobDateString);

    System.out.println("Method 2: " + dobDate);
}
catch (ParseException pe) {
    pe.printStackTrace();
}
Here we'll use the name parameter to fetch the same value. Using the SimpleDateFormat to parse the string we can retrieve the Date object.

Wednesday 19 October 2016

Show webcontent based on artical Id

<%
               
                String articleName = PropsUtil.get("acticle.name");
       
                ThemeDisplay themeDisplay2 = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
                long groupId = themeDisplay.getScopeGroupId();
               
                JournalArticle journalArticle = JournalArticleLocalServiceUtil.getArticleByUrlTitle (themeDisplay.getScopeGroupId(), articleName);
                String articleId = journalArticle.getArticleId();       
               
               
%>
  <liferay-ui:journal-article articleId="<%=articleId %>" groupId="<%=groupId %>">
</liferay-ui:journal-article>


Depends on site...

<%
    PortletPreferences preferences = renderRequest.getPreferences();
    long groupId = GroupLocalServiceUtil.getFriendlyURLGroup(themeDisplay.getCompanyId(), "/ww").getGroupId();
%>

<c:if test="${programDetails.termsAndConditionsArticleId ne 0}">
    <liferay-ui:journal-article articleId="${programDetails.termsAndConditionsArticleId}" groupId="<%=groupId %>" />
</c:if>

Wednesday 28 September 2016

onchange showing result


 <form name="fm"></form>
 <select onchange="companyChange()">
javascript

<script>
function companyChange(){
    alert("Can you Submit...?");
    document.fm.submit();
}
</script>

Jquery

<script>
$("#approvalStatus").change(function(){
alert("Can you Submit...?");
$("form[name='fm']").submit();
});
</script>

Monday 12 September 2016

Currency symbol for all countries



Code to get currency symbol:

    Currency currency = null;
    Locale locale = null;
    String currencySymbol = null;
  /*Get List of available countries from liferay country table*/
    List<Country> countryCode = CountryServiceUtil.getCountries();
   
    for(Country country:countryCode)
    {
        try{
            locale = new Locale.Builder().setRegion(country.getA2()).build();
            currency = Currency.getInstance(locale);   
               currencySymbol = currency.getSymbol(locale);
              System.out.println("currency symbol is......"+currencySymbol);}
        catch(Exception e){
            System.out.println("exception..."+e);
        }
    }

Passing form in ajax call


Submit HTML form with AUI Ajax

In case if you wish to pass html form with aui ajax, you need to change view.jsp code as per below snippet


<portlet:resourceURL var="testAjaxResourceUrl"></portlet:resourceURL>

<form id="testAjaxForm" action="">
    <input type="text" name="<portlet:namespace />param2">
    <input type="button" value="Submit" onclick="ajaxCall()">
</form>

<script type="text/javascript">
function ajaxCall(){
    AUI().use('aui-io-request', function(A){
        A.io.request('${testAjaxResourceUrl}', {
               method: 'post',

               data: {

                   <portlet:namespace />sampleParam: 'value2',
               },
               form:{
                   id:'testAjaxForm'
               },
               on: {
                       success: function() {
                        alert(this.get('responseData'));
                   }
              }
        });
    });
}
</script> 


package com.opensource.techblog.portlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.util.bridges.mvc.MVCPortlet;

public class TestAjaxPortlet extends MVCPortlet {

    private static Log _log = LogFactoryUtil.getLog(TestAjaxPortlet.class.getName());
   
    @Override
    public void serveResource(ResourceRequest resourceRequest,
            ResourceResponse resourceResponse) throws IOException,
            PortletException {
       
        String param = ParamUtil.get(resourceRequest, "param2", StringPool.BLANK);
       
        _log.info("Parameter is ==>" + param);
       
        resourceResponse.setContentType("text/html");
        PrintWriter out = resourceResponse.getWriter();
        out.print("You have entered ==>"+param);
        _log.info("Ajax call is performed");
        out.flush();
        super.serveResource(resourceRequest, resourceResponse);
    }
}
 















We can pass whole form in ajax call by serializing the form

In your script:

var str = $('#<portlet:namespace/>jobform').serialize();
$.ajax({
 type: "post",
 data: str,
 dataType: 'text',
 url: "<%=submitJobURL%>",
 async: false,
 success: function(data) {
  alert("success");
 }
});

And your form view in jsp:
<aui:form method="post" name="jobform">
<aui:input name="jobName" type="text" />
</aui:form>

Here jobform is your form id.

And we can get values in controller by normal way

String jobName = ParamUtil.getString(request,"jobName");

Thanks,
K.Mufas Mohammed Mydeen

Sharing liferay portlet to other website

Sharing liferay portlets is very easy.Liferay provides easy way to bring our portlet in other portals and websites. To share portlet Click on configuration of the portlet. For ex:Click on configuration of blogs portlet


Now you will be seeing a script given in the box.Check allow users to add blogs to any website and save.

Select the script and put in any website code.It will bring you the portlet view there.From there you can add a blog now.

Same thing can be done for any portlets and even for our custom portlets.

Initially if you put the script it will not be displayed.

In browser console you will be getting

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

To resolve this you need to add
In portal-ext.properties

http.header.secure.x.frame.options=false 

and restart your server.It will work.By default it will be displayed.

Liferay Migration From 6.1 to 6.2

Steps for Migration

Step 1: Create dump of liferay6.1(eg : mysqlDump61.sql)

Step 2: Create New Database for Lifeay6.2 (eg: "mysqlDump62.sql")

Step 3: Setup a New Liferay Setup and start the server then finish the Configuration by pointing to the newly Created Database (eg :"mysqlDump62.sql") once setUp Finshed Stop the Server.(Note: Start With Fresh Liferay Bundels)

Step 4: Stop the Liferay6.2 Server.

Step 5: Import Lifeay6.1 dump(eg : mysqlDump61.sql) into Lifeay6.2 Database(eg:"mysqlDump62.sql")

Steps 7: Copy the "data" folder from Liferay6.1 server and replace the Liferay 6.2 "data" folder  with Liferay6.1 "data" folder in Liferay6.2 server.

Steps 8: Add following lines in "portal-setup-wizard.properties" file.

              dl.hook.impl=com.liferay.documentlibrary.util.AdvancedFileSystemHook
              dl.store.impl=com.liferay.portlet.documentlibrary.store.AdvancedFileSystemStore
              passwords.encryption.algorithm.legacy=SHA  // this property helps to remove conflicts in password encryption occurs in migrated database passwords.

Steps 9: Start the Liferay6.2 Server then you can able to notice that updating process taking place wait till update and migration complete.


How to Close Liferay PopUp in Liferay

Step :1

In "view.jsp"

           <liferay-portlet:renderURL var="dialogURL" windowState="                                                                             <%=LiferayWindowState.POP_UP.toString() %>">

    <liferay-portlet:param name="jspPage" value="/html/dialog.jsp" />
    </liferay-portlet:renderURL>

    <aui:button  name="openDialog" type="button" value="open-dialog" />

// If you  Click on "openDialog"  button popup will be triggered and opened, in that "content.jsp" content's will be loaded.If you Click on "closeDialog" button  popUp  will be closed



    <aui:script use="liferay-util-window">

    A.one('#<portlet:namespace/>openDialog').on('click', function(event) {
    Liferay.Util.openWindow({
    dialog: {
    centered: true,
    height: 300,
    modal: true,
    width: 400
    },
    id: '<portlet:namespace/>dialog',
    title: '<liferay-ui:message key="i-am-the-dialog" />',
    uri: '<%=dialogURL %>'
    });
    });
  
// this below code will helps to Close the popup, once the action triggered from the child page "content.jsp"

Liferay.provide(
     window,
     'closePopup',
     function(dialogId) {
     var dialog = Liferay.Util.getWindow(dialogId);

     Liferay.fire(
     'closeWindow',
     {
    
     id:'<portlet:namespace/>dialog'
     }
     );
     },
     ['aui-base','liferay-util-window']
     );

    </aui:script>


Step 2:

In "content.jsp"



<%@page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
  
  
    <aui:button name="closeDialog"  type="button" value="close" />
    
    <aui:script use="aui-base">
    A.one('#<portlet:namespace/>closeDialog').on('click', function(event) {
    
    // Let's suppose that "data" contains the processing results

    // Invoke a function with processgin results and dialog id
     Liferay.Util.getOpener().closePopup('<portlet:namespace/>dialog');// this will will call the closePopup fuction in parent page where the popUp is initiated "view.jsp".

    });
    </aui:script>
  

Liferay - Custom Password Validation (Strength)

Custom password validation strength based on password poloices


  • Lowercase character        eg:RegExp   (?=.*[a-z])
  • Uppercase character        eg:RegExp   (?=.*[A-Z])
  • Digit                                   eg:RegExp   (?=.*[0-9])
  • Symbol                              eg:RegExp   (?=.*[@#$^&*!~])
 I am using Regular Expression   

<aui:input id="newPassword" name="newPassword" type="password"
                                placeholder="New Password" label="">

        <aui:validator  name="custom"  errorMessage="Password should contain atleast one
 (Uppercase Letter,lowercase Letter,Numeric digit and Symbol)" >
                                                                        
          function(val, fieldNode, ruleValue) {
              var passwordPattern = new RegExp("(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[@#$^&*!~])");
                           var result = passwordPattern.test(val);
                                    if(result){
                                             return result;
                                        }else{
                                               return result;
                                            }
                                    }
           </aui:validator>     
 </aui:input>

Tuesday 6 September 2016

Liferay 6.2 Portal-Properties

Liferay Service Builder Concept

Theme display signed in or Not signed in

<%if(themeDisplay.isSignedIn()){ %>
       <aui:a href="<%=demoscheduleAdd.toString() %>"><button class="demoform">Schedule Demo</button></aui:a>
       <%}else { %>
       <a href="/course_catalog?p_p_id=58&p_p_lifecycle=0&p_p_state=maximized&p_p_mode=view&saveLastPath=false&_58_struts_action=%2Flogin%2Flogin"> <button class="demoform">Schedule Demo</button></a>
       <%} %>  

portal-ext.properties code

portal-ext.properties

jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.url=jdbc:mysql://localhost/dbname?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
jdbc.default.username=root
jdbc.default.password=root