We used cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it. What For?

Liferay 7-DXP Model Listener Hook

Model Listener is used to listen to  Liferay Model Events. We can perform custom action on Before/After the persistence event of Model objects using Model Listener. Model Listeners implement ModelListener interface. They are useful in terms of processing, custom login on Model objects while they are added/updated/removed. For ex, if we want to perform any specific action before User is created then we can implement the Model Listener for User model and perform actions on onBeforeCreate method. This would be invoked before persistence layer’s create method.

 

Prerequisite :

Basic knowledge of Liferay 7 Development and Liferay Hooks

 

We were used to create Hook plugin in previous Liferay versions to create Model Listener hook. Here, we will be creating Module project with Model Listener implementation for Role model. We will be using ModelListener.class as a service Component class of our module. We will implement ModelListener for Role model which will be called before/after on persistence events of Role entity.

 

First of all, create a module project for custom listener class.  Consider below code for @Component annotation of Module Class.

 

@Component(

immediate = true,

service = ModelListener.class

)

 

Now you need to extend BaseModelListener<Role> class in order to override listener methods from parent class for Role entity. For example, consider below code where I have overriden onAfterCreate and onBeforeCreate methods.

 

public class MyCustomRoleModelListenerPortlet extends BaseModelListener<Role> {


@Override

public void onAfterCreate(Role model) throws ModelListenerException {

System.out.println("MyCustomRoleModelListenerPortlet.onAfterCreate()");

// Write your custom Logic

super.onAfterCreate(model);

}


@Override

public void onBeforeCreate(Role model) throws ModelListenerException {

System.out.println("MyCustomRoleModelListenerPortlet.onBeforeCreate()");

// Write your custom Logic

super.onBeforeCreate(model);

}

}

 

When you will deploy this module/hook into Liferay DXP/7 portal, it will call above methods before and after creating a Role from Control Panel.

 

You can implement any of the below listener methods in Model Listener Hook.

 

onBeforeCreate

onBeforeUpdate

onBeforeRemove

onBeforeAddAssociation

onBeforeRemoveAssociation

onAfterCreate

onAfterUpdate

onAfterRemove

onAfterAddAssociation

onAfterRemoveAssociation

 

That’s all. You can create Model Listener Hook in Liferay 7 with the help of mentioned steps.

 
contact-us Request a callback WhatsApp