How to save info into Contentlet using custom plugin

I had some issues not that long ago figuring out how to build a dotCMS plugin that would save custom data in to a particular structure and wasn't finding much helpful stuff on the internet. I thought I would share my knowledge so someone who might be in my shoes won't have similar issues.  I will note that I am working on dotCMS version 2.5.7.

I will break it down into simple steps and post some code snippets in here to make it easy to follow along

Step one

Create a new contentlet object like this  

Step two

Next we need to get the Structure that we're saving to.  We get the respective structure object by finding it with it's string title "BulkMailing" with the `getStructureByName()` method.

Contentlet checkins require a structure inode.  The structure inode is in the structure object we just got.  We move the structure inode in to our soon-to-be-checked-in contentlet object like this.

Step three

Now from here, it is as simple as setting our contentlet field properties

Using the contentlet object's setStringProperty() method, the first argument is the structure field name and the second is the respective value.  For example, we have the field "email" and we're setting that to the value represented by the String `email` variable.  Some goes for the "date" field (with respective data types, of course).

 

Step four

Now check in our contentlet.  We use the DotCMS APILocator to get at the  ContentletAPI's checkin() method which requires 3 arguments.  The first argument is our soon-to-be-published contentlet (of "Contentlet" data type).  The second represents the user publishing the contentlet ("User" data type).  The 3rd is a boolean flag we use to indicate whether or not we want to respect front-end roles.

Then simply publish, again using the Contentlet API.

That should do it.  You are now able to save data using a plugin into a structure that exists in your backend.

Leave a comment if I can help clarify or answer any questions.

Say Hello

Near the Cleveland, Akron or Medina area and want to stop by our office? Let us know and we'll get the coffee and whiteboards ready. :)