alpa
alpa

Reputation: 87

Liferay ModelListener for JournalArticles not showing Title

I am new to Liferay and am working on a model writer for Web Content Articles (Journal Articles). It is important to keep the title and the content after the creation. I have written a simple script for this. However, the output title is empty and the content is zero.
The article object itself does not contain a key for title or content. Unfortunately, I don't know what to do and hope that someone has already had experience with this.

package webcontenthandler;

import com.liferay.journal.model.JournalArticle;
import com.liferay.journal.service.JournalArticleLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.model.BaseModelListener;
import com.liferay.portal.kernel.model.ModelListener;
import org.osgi.service.component.annotations.Component;

import java.util.List;

@Component(
        immediate = true,
        service = ModelListener.class
)
public class WebContentHandler extends BaseModelListener<JournalArticle> {

    @Override
    public void onAfterCreate(JournalArticle article) {
        try {
            JournalArticle myarticle = JournalArticleLocalServiceUtil.getArticle(article.getGroupId(), article.getArticleId(), article.getVersion());
            System.out.println("article: " + myarticle);
            System.out.println("article content: " + myarticle.getContent());
            System.out.println("article title: " + myarticle.getTitle());
            System.out.println("article title: " + myarticle.getTitleCurrentValue());
        } catch (PortalException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Class<JournalArticle> getModelClass() {
        return JournalArticle.class;
    }
}

Upvotes: 0

Views: 29

Answers (1)

Olaf Kock
Olaf Kock

Reputation: 48087

It's been a long time since I wrote ModelListeners, but there are several issues that I see for investigation. Some candidates for finding the root cause of this issue, some just style:

#1, you're implementing an OSGi component, which means that you should not use JournalArticleLocalServiceUtil, but rather implement a member @Reference JournalArticleLocalService jals;.

#2: the method's signature is public void onAfterCreate(JournalArticle article), and the first thing you do is to retrieve the article from the database. With what you describe, I'd assume that the transaction has not yet been committed - e.g. the article is not yet available in the database. But you have it at hand anyway from the parameter to this method - why retrieve it from the database anyway?

#3: It's typically somewhat closer to the business layer if you rather implement a ServiceWrapper than a ModelListener

Item 1 would be overturned (e.g. unnecessary) by implementing 2 and/or 3, but it's worth keeping that technique in mind for other cases.

Upvotes: 0

Related Questions