How to Set a Date Time Customfield by Postfunction

Hi,

this is for info to the community: We had to set a customfield "StartTime" of type "Date Time" automatically in a postfunction via script (groovy) with the current time.

2 answers

1 accepted

Here is the complete code. It includes a hack to share the code to be used as a postfunction and developed with Script Runner webinterface (https://jira/secure/admin/groovy/GroovyRunner.jspa) - some additional debugging code included:

import org.apache.log4j.Category
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder

log = Category.getInstance(env="post-set-starttime.groovy") // env="SR" if used within Script Runner webinterface
// log.warn "begin"

// issue is provided by environment when used as a postfunction
if (env == "SR") issue = componentManager.getIssueManager().getIssueObject(97328)
// log.warn "issue "+issue.getKey()
cfm = componentManager.getCustomFieldManager()
ch  = new DefaultIssueChangeHolder();
cfo = cfm.getCustomFieldObjects(issue).find {it.name == 'StartTime'}
cfv = issue.getCustomFieldValue(cfo)
if (! cfv) {
  t0  = new java.sql.Timestamp(System.currentTimeMillis())
  log.warn "StartTime => '"+t0.toString()+"'"
  if (env == "SR") { // Script Runner code
    mv = new ModifiedValue(cfo, t0)
    ch = new DefaultIssueChangeHolder()
    cfo.updateValue(null, issue, mv, ch)
  } else { // postfunction code
    issue.setCustomFieldValue(cfo, t0)
    issue.store()
  }
} else {
  log.warn "StartTime == '"+cfv.toString()+"'"
}
// log.warn "end"
What is 97328 in getIssueObject(97328)?

'env' is set to "SR" if we test our scripts on example data and in this case the issue with the id 97328 was our example issue.

Normally this script works as a postfunction. In this case there is no 'env' variable defined and 'issue=...' is not executed, the object issue is defined by groovy environment.

Suggest an answer

Log in or Sign up to answer
How to earn badges on the Atlassian Community

How to earn badges on the Atlassian Community

Badges are a great way to show off community activity, whether you’re a newbie or a Champion.

Learn more
Community showcase
Published Jul 10, 2018 in Marketplace Apps

If you’re an Atlassian app developer, you’ll want to know about Atlas Camp!

This September 6-7, hundreds of Atlassian App developers will flock to Barcelona Spain to build skills, discover product roadmaps, meet face-to-face with the Atlassian team, and learn how to extend t...

179 views 0 4
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you