Update field in compound type using groovy script

Hi,

How to update a field present in the compound type using groovy script?

I’am using something like this hbook:primaryTaxonomy/@hbook:firstLevel to access the compound field. Where firstLevel is a dropdown string field.

class ChangeTax extends BaseNodeUpdateVisitor {
 
  private static final NEW_TAG = 'hbook:primaryTaxonomy/@hbook:firstLevel'
 
  boolean doUpdate(Node node) {
    try{
        def taxvalue
        //log.debug "Node Name ${node.path}"
        //Fetch current value
        taxvalue = node.getProperty("hbook:primaryTaxonomy/@hbook:firstLevel").getValue()
        log.debug "Tag Value is ${taxvalue}"

        //Update value to ourstory
        node.setProperty(NEW_TAG, 'ourstory');
        return true;
    }catch(e) {
      return false;
    }
  }

boolean undoUpdate(Node node) {
throw new UnsupportedOperationException('Updater does not implement undoUpdate method')
}

}

Please suggest.

Thanks,
RK

Hi RK,

You can get the compound node first to get and set properties, using JCR API [1]:

  if (node.hasNode("hbook:primaryTaxonomy")) {
    def compoundNode = node.getNode("hbook:primaryTaxonomy")
    if (compoundNode.hasProperty("hbook:firstLevel")) {
      def value = compoundNode.getProperty("hbook:firstLevel").getString()
      //...
    }
    //...
    compoundNode.setProperty("hbook:firstLevel", "ourstory")
  }

You can also use the utility, org.hippoecm.repository.util.JcrUtils, to avoid exceptional cases such as non-existing node or illegal access, etc. For example,

import org.hippoecm.repository.util.JcrUtils
//...
  def compoundNode = JcrUtils.getNodeIfExists(node, "hbook:primaryTaxonomy")
  if (compoundNode != null) {
    def value = JcrUtils.getStringProperty(compoundNode, "hbook:firstLevel", null)
    //...
    compoundNode.setProperty("hbook:firstLevel", "ourstory")
  }

Regards,

Woonsan

[1] https://docs.adobe.com/docs/en/spec/javax.jcr/javadocs/jcr-2.0/index.html

Awesome, thanks! Will give a try.