Showing posts with label liferay ui custom attribute. Show all posts
Showing posts with label liferay ui custom attribute. Show all posts

Friday, February 14, 2014

Working with Liferay Custom Fields

Introduction:

Liferay has very good feature that is Custom Fields, from this we can create additional attributes or new fields to existed entities.

Please go through following Tutorial for Introduction


Environment:

Liferay 6.2 +Tomcat 7.x+MySQL 5.1

Note:

The code will work for portal 6.2 version you can try for 6.1 too.

Download Liferay Custom Fields Portlet from following location

You can find source and war file


Portlet Screen1:


Portlet Screen2:


Portlet Screen3:



Procedure for deploy portlet:

You can use war file and directly place in your portal deploy folder and test or you can also use source to deploy portlet.

Once portlet is deployed successfully you can see the portlet in sample category name as Liferay Custom Fields.

Note:

Before use this portlet please Read entire Article and Use it

Implementation

Now we will see how to use custom filed in real time development.
We are going create new custom fields to user so that we can add additional information user.Assume we are creating Custom Fields to User Entity
  1. Create Custom Fields
  2. Using Custom Fields in Plugin Portlet Development

Create Custom Fields

We need create required custom attributes to user entity from liferay portal admin screen.
Assume we want create two custom fields to track user education details and  I am choosing select input and text input as my requirement.

Login as Portal Admin and go to Admin Control Panel

The following screen show control panel link


As soon as we click we can go Admin control panel there we can see many admin sections

The following screen show Admin Control Panel and sections



In the configurations section we can see Custom Fields Link. We need to click on that and we will go to the custom field’s screen

The following is all entities witch support Custom Field Feature. Now we are going to create custom fields for User. You can click on User entity link


As soon as we click on User entity we can see following screen



We have button called add custom filed button when we click button it will go to add custom field screen there it will ask custom field key and its type

The following is create custom field screen



We can create many types of fields like text box, select like all form fields apart from that we can also have choice to select fields accept data type too. The above screen in type field you can see all possibilities

Now we need to give attribute key and type then we can save custom field.

Here very important is attribute key we will use this as reference to access custom field.
Once we save then you can see following screen where you can see all list of custom fields and its properties


We can also have edit and set permission to custom fields.

The following screen shows you edit and permission options



The following screen shows you permission screen for custom field


Assume we have created select Field as follows and we click on save then field will be saved.



To fill options to select box we need click on edit field then we can get more properties as follows


In the above screen there you can find values input field there I passed required select options with comma separate. After completion of edit you can save the field

The following is example for Text Field


Now we have created two custom fields for user and one is select box another one is text box
The following screen shows Available Custom Fields for User


Now we have done creation of custom fields to user

View User Custom Fields

To view custom fields for user we need to go MY Account page there you can see custom field section.

When you click on custom fields you call see available custom fields to user there you add or update the data.

The following is screen show navigate to my account page


The following screen shows custom fields for user and we can add or update data here



Using Custom Fields in Plugin Portlet Development

Before going to use custom fields we need to ready with custom fields

The following is code for Display Custom Fields as Editable Mode

<%@page import="com.liferay.portal.model.User"%>
<%@ include file="init.jsp" %>
<%
User selUser=themeDisplay.getUser();

%>
<portlet:actionURL  var="updateUserCustomeAttributeURL" 
name="updateUserCustomeAttributes">
</portlet:actionURL>
<aui:form action="<%= updateUserCustomeAttributeURL %>" method="post" name="fm">
<aui:input name="currentUserId" value="<%=user.getUserId()%>" type="hidden"/>
<liferay-ui:custom-attribute-list
className="<%= User.class.getName() %>"
classPK="<%= selUser != null ? selUser.getUserId() : 0 %>"
editable="<%= true %>" label="true"/>
<aui:button type="submit" value="update"/>
</aui:form>  

Update Data for User Custom Fields

The following is code we need place in Portlet Action Class to Update/Add Data

public void updateUserCustomeAttributes(ActionRequest actionRequest, ActionResponse actionResponse)throws IOException,
 PortletException, PortalException, SystemException {
ServiceContext serviceContext = 
ServiceContextFactory.getInstance(User.class.getName(), actionRequest);
long currentUserId = ParamUtil.getLong(actionRequest,"currentUserId");
User user=UserLocalServiceUtil.getUser(currentUserId);
user.setExpandoBridgeAttributes(serviceContext);
UserLocalServiceUtil.updateUser(user);
}

View Custom Field Data in JSP Page

<%
User selUser=themeDisplay.getUser();
%>
<h2>User Education Details</h2>
<liferay-ui:custom-attribute-list
className="<%= User.class.getName() %>"
classPK="<%= selUser != null ? selUser.getUserId() : 0 %>"
editable="<%= false %>" label="true"/>
<aui:button type="submit" value="update"/>

Display Single Field as Editable

<%
User selUser=themeDisplay.getUser();

%>
<h2>User Education Details</h2>
<liferay-ui:custom-attribute
 className="<%= User.class.getName() %>"
 classPK="<%= selUser != null ? selUser.getUserId() : 0 %>"
editable="<%= true %>"
name="Qualification" label="true"/>

View Single Field Data

<%
User selUser=themeDisplay.getUser();
%>
<h2>User Education Details</h2>
<liferay-ui:custom-attribute
 className="<%= User.class.getName() %>"
 classPK="<%= selUser != null ? selUser.getUserId() : 0 %>"
editable="<%= false %>"
name="Qualification" label="true"/>

Note:

Validation for this is not straight forward way we need use Java Script and we need to apply manually.
Author

Introduction to Liferay Custom Attributes/Custom Fields

Introduction:

Liferay have come up with custom attributes which help us to add additional fields to existed models/entities.

This will help us to add some more additional attributes to existed entities so that we can meet your requirements.

This pretty easy we can configure from Admin screen in Liferay Portal.

Liferay have given this feature to many existed entities such as User, Organization, Role and Site many more.

The following screen shows you liferay entities that liferay support custom attributes


What is use of custom attributes?

Custom attribute the way to add additional attributes to existed portal entities so that in our real requirement if any fields you wanted then you can add.

Example:

For User registration you may need special field but existed user table may not have that fields then you can create new filed so that you can use in user registration.

How can I create Custom attribute/Custom fields?

This is pretty easy and simple you can login as admin and go to control panel there you can see the custom fields link as soon as you click you can navigate to custom fields screen.

Where can I see custom fields?

It depends and for a user we can see in custom fields section there you can find all custom fields and you can also use in development. Liferay have UI tags for to show custom files through program.

Access Custom fields in program

User Custom Fields

user.getExpandoBridge().getAttribute("attirbute-key")

Role Custom Fields

role.getExpandoBridge().getAttribute("attirbute-key")


Site Custom Field

site.getExpandoBridge().getAttribute("attirbute-key")


Another way to access Custom Attributes


com.liferay.portlet.expando.model.ExpandoValue expandoObiect=ExpandoValueLocalServiceUtil.getValue(classNameId, tableName, columnName, classPK)
String fieldValue=expandoObiect.getData();


Example to Get User Custom Attribute


com.liferay.portlet.expando.model.ExpandoValue expandoObiect=ExpandoValueLocalServiceUtil.getValue
(ClassNameLocalServiceUtil.getClassNameId(User.class), "CUSTOM_FIELDS", "Mobile Number", curUser.getUserId())


Note:

You can see the ExpandoTables and ExpandoValue entity related classes in portal source code

The following are some of the important java classes


ExpandoTableLocalServiceUtil
ExpandoValueLocalServiceUtil
ExpandoValue
ExpandoTable


Note:

 Attribute key is field name this is we will give as input when we create custom filed

Display Custom Attribute as Input Fields

Liferay have Liferay UI tag library one of the tag is custom attribute tag form this we can show custom attribute as input filed. This will help us update/add new values to custom attributes

Note:

This tags we will use on JSP pages so we need to add Liferay UI tag library in the page


<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>


We have two tags


<liferay-ui:custom-attribute/>
<liferay-ui:custom-attribute-list />


<liferay-ui:custom-attribute/>

Custom attribute tag will display only one input files and it will take custom attribute name and respective model class as attributes

Tag Syntax


<liferay-ui:custom-attribute classPK="" name="" className=""></liferay-ui:custom-attribute>      


The following are the attributes for above tag

className(required = true):

The fully qualified name of the entity e.g. com.liferay.portal.model.User

classPK(required = true):

The primaryKey of the entity instance (or zero (0) if there is not currently an instance)

Name (required = true):

 The name of the specific attribute to render and its key of attribute we have given at the time of field creation as admin.

Editable:

It takes true or false values based on that we can edit the value in the input text box.

Label:

It is label for display filed it will take true/false.

Example:

Display User Custom Filed in JSP page


<%User user=themeDisplay.getUser();%>
<liferay-ui:custom-attribute
className="<%= User.class.getName() %>"classPK="<%= user!= null ? user.getUserId() : 0 %>"
editable="<%= true %>"
name="company-name"
label="true"/>


<liferay-ui:custom-attribute-list />

Custom attribute list tag display all custom fields for respective entity.

Tag Syntax


<liferay-ui:custom-attribute-list classPK="" className="">
</liferay-ui:custom-attribute-list>    
       

The following are the attributes for above tag

className(required = true):

The fully qualified name of the entity e.g. com.liferay.portal.model.User

classPK(required = true):

The primaryKey of the entity instance (or zero (0) if there is not currently an instance)

Name (required = true):

 The name of the specific attribute to render and its key of attribute we have given at the time of field creation as admin.

Editable:

It takes true or false values based on that we can edit the value in the input text box.

Label:

It is label for display filed it will take true/false.

IgnoreAttributeNames:

This will take attribute names that is you don’t want to display and its string value you need pass multiple values with COMMA separate.

Example:

Display User All Custom Fields in JSP page


<%User user=themeDisplay.getUser();%>
<liferay-ui:custom-attribute-list
className="<%= User.class.getName() %>"
classPK="<%= user!= null ? user.getUserId() : 0 %>"
editable="<%= true %>" label="true"/>


Update/Set the value to Custom Fields


Set User Custom Fields

user.getExpandoBridge().setAttribute("custome- attirbute-key ", "value");

Set  Role Custom Fields

role.getExpandoBridge().setAttribute("custome- attirbute-key ", "value");

Set  Site Custom Field

site.getExpandoBridge().setAttribute("custome- attirbute-key ", "value");



Example:


user.getExpandoBridge().setAttribute("company-name", "My Company");


Another way to add data/set value to Custom Fields


ExpandoValueLocalServiceUtil.addValue(classNameId, tableId, columnId, classPK, data);


Example:


ExpandoValueLocalServiceUtil. addValue (ClassNameLocalServiceUtil.getClassNameId(User.class), "CUSTOM_FIELDS", "Mobile Number", curUser.getUserId(),”90898990”)


Note:

You can see the ExpandoTable and ExpandoValue entity related classes in portal source code

The following are some of the important java classes


ExpandoTableLocalServiceUtil
ExpandoValueLocalServiceUtil
ExpandoValue
ExpandoTable


Search Data with Basis of Custom Fields

We can also perform search with basis of custom attributes

The following is simple search methods with custom attributes for User Entity


public static com.liferay.portal.kernel.search.Hits search(long companyId,
                        java.lang.String keywords, int status,
                        java.util.LinkedHashMap<java.lang.String, java.lang.Object> params,
                        int start, int end, com.liferay.portal.kernel.search.Sort sort)
                       

public java.util.List<com.liferay.portal.model.User> search(
                        long companyId,keywords, int status,
                        java.util.LinkedHashMap<java.lang.String, java.lang.Object> params,
                        int start, int end, com.liferay.portal.kernel.util.OrderByComparator obc)
                        throws com.liferay.portal.kernel.exception.SystemException


Example Search Users with basis of Custom Fields/Custom Attributes

Example: 1


LinkedHashMap userParams = new LinkedHashMap();
userParams.put("company-name", "vinculum");
boolean asc = true;
Sort sortOrderByAttribute = new Sort("lastName", Sort.STRING_TYPE, asc);
Hits hits = UserLocalServiceUtil.search(companyId, null, true, userParams, 0, 20, sortOrderByAttribute);
List<User> users =UserLocalServiceUtil.search(companyId, null,WorkflowConstants.STATUS_ANY,userParams, 0, 20,null);


Example: 2


LinkedHashMap userParams = new LinkedHashMap();
userParams.put("company-name", " vinculum ");
boolean asc = true;
Sort sort = new Sort("lastName", Sort.STRING_TYPE, asc);
Hits hits = UserLocalServiceUtil.search(companyId, null, true, userParams, 0, 20, sort);
List<User> users = new ArrayList<User>();
List<Document> hitsList = hits.toList();
for (Document doc : hitsList) {
            long userId = GetterUtil.getLong(doc.get(Field.USER_ID));
            users.add(UserLocalServiceUtil.getUserById(userId));
}



All observations I have done in Loferay 6.2 CE version and you can see similar things in lower version of liferay too and may be some changes we can expect in lower versions.

Author

Recent Posts

Recent Posts Widget

Popular Posts