Create Object with Context Data EventListener

Last modified by Anca Luca on 2026/08/05 17:15

cogCreates a new object on the user profile and saves the data filled in by the user
TypeSnippet
Category
Developed by

Oana Florea

Rating
0 Votes
LicenseGNU Lesser General Public License 2.1

Table of contents

Description

This snippet allows the user to update a property value for an object that has not been yet added to a wiki page (e.g. a new object of type Code.MyNewClass on the user profile). The user sheet can be updated to display the input field for the new property even if the object does not exist yet:

#set($objNumber = 0)
#set($newClassName = 'Code.MyNewClasss')
#set($newPropertyName = 'myNewProperty')
#set($newObj = $doc.getObject($newClassName ))
#if($newObj)
  #set($objNumber = $newObj.number)
  #set($myNewPropertyValue = $newObj.getProperty($newPropertyName).value)
#end
<input type="text" name="${newClassName}_${objNumber}_${newPropertyName}" value="$!{myNewPropertyValue}" id="${newClassName}_${objNumber}_${newPropertyName}" size="30"/>{{/html}} \\

This event listener adds the new object on the user profile and fills in the data added by the user:

import org.xwiki.observation.*
import org.xwiki.observation.event.*
import org.xwiki.bridge.event.*
import org.xwiki.context.*
import com.xpn.xwiki.web.*
import com.xpn.xwiki.*
import org.apache.velocity.VelocityContext;
import org.slf4j.LoggerFactory;

class MyUpdater implements EventListener
{
    def LOGGER = LoggerFactory.getLogger("MyUpdater");
  
    String getName()
    {
        // The unique name of this event listener
        return "MyUpdater"
    }

    List<Event> getEvents()
    {
        // The list of events this listener listens to
        return Arrays.asList(new DocumentCreatedEvent(), new DocumentUpdatedEvent())
    }

    // Called by the Observation Manager when an event matches the list of events returned
    // by getEvents()
    void onEvent(Event event, Object source, Object context)
    {
        // Current context
        def crtContext = Utils.getComponent(Execution.class).getContext().getProperty('xwikicontext')

        // Defines the type of documents that should be looked for (e.g. documents which have and object of type XWiki.XWikiUsers)
        def myObject = source.getObject("XWiki.XWikiUsers");
        // the class name of the new object I want to add to the user profiles
        def newClassName = 'Code.MyNewClass';
        def newPropertyName = 'myNewProperty';
        // the new object will always be the first one
        def newObjectName = newClassName + '_0_' + newPropertyName;
        // get the data the user filled in for myNewProperty when he saved the wiki page 
        def newObjectValue = context.getRequest().get(newObjectName);
        LOGGER.warn("new object value=" + newObjectValue);
        // check the document has the type I am searching for
        if (myObject != null) {
          // check if the page has already a new object attached
          def newObj = source.getObject(newClassName);
          if (newObj == null) {
            LOGGER.warn(source.getFullName() + " is missing my new object");
            newObj = source.newObject(newClassName, crtContext);
            newObj.set(newPropertyName, newObjectValue, crtContext);
            // Force the storage to keep the same version number, so that this looks like a single save event
            source.setMetaDataDirty(false);
            source.setContentDirty(false);
            crtContext.getWiki().saveDocument(source, source.getComment(), source.isMinorEdit(), crtContext);
          } else {
            LOGGER.warn(source.getFullName() + " already has an a new object");
          }
        }        
    }
}

// Register against the Observation Manager
def observation = Utils.getComponent(ObservationManager.class)
observation.removeListener("MyUpdater")
def listener = new MyUpdater()
observation.addListener(listener)

Get Connected