The Model Listener sample demonstrates adding a custom model listener to a
Liferay Portal out-of-the-box entity. When deploying this sample with no
customizations, a custom model listener is added to the portal’s layouts,
listening for onBeforeCreate
events. This means that any page creation will
trigger this listener, which will execute before the new page is created.
For example, if a new page is added with the name My Test Page, the following message is printed to the console:
Figure 1: The sample model listener's message in the console.
You can also verify that the model listener sample was executed by navigating to the new page’s Options → Configure Page → SEO option. The HTML Title field looks like this:
Figure 2: The page's HTML title updated by the model listener sample.
What API(s) and/or code components does this sample highlight?
This sample leverages the ModelListener API.
How does this sample leverage the API(s) and/or code component?
Model Listeners are used to listen for persistence events on models and take
actions as a result of those events. Actions can be executed on an entity’s
database table before or after a create
, remove
, update
, addAssociation
,
or removeAssociation
event. It’s possible to have more than one model listener
on a single model too; the execution order is not guaranteed.
There are two steps to create a new model listener:
- Implement a Model Listener class
- Register the new service in Liferay’s OSGi runtime
This sample adds the model listener logic in a new Java class named
CustomLayoutListener
that extends
BaseModelListener.
public class CustomLayoutListener extends BaseModelListener<Layout> {
@Override
public void onBeforeCreate(Layout model) throws ModelListenerException {
System.out.println(
"About to create layout: " + model.getNameCurrentValue());
model.setTitle("Title generated by model listener!");
}
}
Important things to note in this code snippet are
- The entity to be targeted by this model listener is specified as the
parameterized type (e.g.,
Layout
). - The overridden methods dictate the type of event(s) that are listened for
(e.g.,
onBeforeCreate
); they also trigger the logic execution.
The final step is registering the service in Liferay’s OSGi runtime, which is accomplished by the following annotation (if using Declarative Services):
@Component(immediate = true, service = ModelListener.class)
For more information on model listeners, see the Creating Model Listeners tutorial.
Where Is This Sample?
There are three different versions of this sample, each built with a different build tool: