Basic method to update a custom field with Scriptrunner

Paddy Byrne April 13, 2016

Hi,

Almost embarrassed to ask this! I am trying to update the displayed value of a simple one line text custom field.

I have read many example online but can't figure it out. I'm using script console, so my issue context is hard-coded:

import com.atlassian.jira.component.ComponentAccessor
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def issueManager = ComponentAccessor.getIssueManager()
def issue = issueManager.getIssueObject("GEO-6")
def String myval = "my new text"
def textCf2 =customFieldManager.getCustomFieldObjectByName("hidden_start")
issue.setCustomFieldValue(textCf2, myval)

I am certain the field name is correct. The script seems to execute fine, and shows no errors in log after it runs, however the value of my custom field never actually updates when I go back and view my issue. What am I doing wrong?

(JIRA 7.1.4 & Scriptrunner 4.2.0.7)

Any help appreciated

2 answers

1 accepted

7 votes
Answer accepted
Paddy Byrne April 13, 2016

Found another way that works:

import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.component.ComponentAccessor
def issueManager = ComponentAccessor.getIssueManager()
def issue = issueManager.getIssueObject("GEO-6")
def String myval = "my new text"
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def textCf2 = customFieldManager.getCustomFieldObjects(issue).find {it.name == "hidden_start"}
if (textCf2) {
    def changeHolder = new DefaultIssueChangeHolder()
    textCf2.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(textCf2), myval),changeHolder)
}

 

My initial effort was following a guide I found here:

Scriptrunner site

Maybe it should be updated as it doesn't seem to be accurate?

Thanos Batagiannis _Adaptavist_
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
April 14, 2016

Hi Paddy

Glad that you find the solution. Just a correction, the script you were looking was for a post function. And actually there is a message:

You can only use this method to update issue attributes if your script post-function comes before the standard functionUpdate change history for an issue and store the issue in the database. If you need your function to run after that, you have to use a more complex method.

Which means if you try to run it via script console you will need somehow to store the issue in the database, and this is what the 

textCf2.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(textCf2), myval),changeHolder)

does.

Kind regards

Like # people like this
Paddy Byrne April 14, 2016

Thank you for clearing that up for me, I did not read the instructions properly!

I understand now I was effectively updating the field but not saving it. I appreciate the explanation

Artur Martins February 21, 2017

Hi, how can I use to update with a number?

 

regards

Paddy Byrne February 22, 2017

Hi Artur - I'm guessing the field you are trying to update can is some kind of text field?

If so, the value you are trying to enter into the target field can be cast to a string with something like

def String myval = MyResultAsNumber.toString()

and then it should work. Or change the target field to number compatible type..

Artur Martins February 22, 2017

I want to get the value that I am bringing from the variable "RESULT.AVERAGE_SEC" to display it in customfield.

Id of my customField: 11300

Part of my code:

def result = sql.firstRow(s)
log.warn "${result.AVERAGE_SEC}"

def customField = result.AVERAGE_SEC
def customField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(11300);
if(customField != null) {
issue.getCustomFieldValue(customField);
}

 but is something wrong because I need to show the value of RESULT.AVERAGE_SEC into my custom field

Paddy Byrne February 22, 2017

Hi - you have defined customField twice and seem to only get its value, not write to it.

Did my best to merge the snippet you gave with code I know works:

def customFieldManager = ComponentAccessor.getCustomFieldManager()
def TargetCF1 = customFieldManager.getCustomFieldObject("customfield_11300")
def result = sql.firstRow(s)
log.warn "${result.AVERAGE_SEC}"
def String myval = result.AVERAGE_SEC.toString()
if (TargetCF1) {
    def changeHolder = new DefaultIssueChangeHolder()
    TargetCF1.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(TargetCF1), myval),changeHolder)
}

I don't really understand where "result.AVERAGE_SEC" comes from, but if it is writing a value to the log in your log.warn statement, then it should get written to your CF

Artur Martins February 24, 2017

Paddy Byrne, it worked for me, but I made some changes

 

def avgValue = ""
def result = sql.firstRow(s) avgValue = "${result.AVERAGE_SEC}" log.warn avgValue

issueInputParameters.with {projectId = projectManager.getProjectObjByKey(key[0]).idsummary = summaryCurrent + " ~ ISR"reporterId = user.name issueTypeId = tipo setDueDate(dateValue)assigneeId = userOm setPriorityId(issueCurrent.getPriorityObject().getId())addCustomFieldValue(11300, avgValue) }
 
11300 is my custom field.
Thank you

 

 

Roberto L
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 25, 2017

Hi @Paddy Byrne and @Thanos Batagiannis _Adaptavist_,

I have been running into issues regarding getting custom fields to update with ScriptRunner.

I came accross your post and tried out your code with no success.

I am trying to update the value of a custom field of type checkbox. My code runs within a Behaviour.

Code:

//utilized same code as you have to grab the customField manager as well as the issue which I name documentIssue

def String myval = "Yes"
def textCf2 = customFieldManager.getCustomFieldObjects(documentIssue).find {it.name == "DEV Reviewd"}

if (textCf2) {
def changeHolder = new DefaultIssueChangeHolder()
textCf2.updateValue(null, documentIssue, new ModifiedValue(documentIssue.getCustomFieldValue(textCf2), myval),changeHolder)
} else log.debug( "Cannot update the value :( " )

 

I fail to understand why it is not working, perhaps its because it is of type checkbox? I have tried many other articles but have not found anyway that works for me.

I would appreciate if you could provide some guidance on this :).

-Roberto

Thanos Batagiannis _Adaptavist_
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 25, 2017

Hi Roberto,

You mentioned that you are trying to set a value to a checkbox in a behaviour right ?

Then please take a look at this example in the documentation - Setting Defaults for Selects etc 

The example code in this thread is for updating the value of a custom field in a post function or via the script console. 

Roberto L
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
August 25, 2017

Hi @Thanos Batagiannis _Adaptavist_,

Thank you for that link, it has helped me in figuering out the answer to my issue!

Thank you!

-Roberto

IJ August 21, 2019

Hi All, I have implemented a single select text field.  I plan to use it as a Script Runner listener to fire when an issue is assigned to someone (setting the "Regional Team" custom field based on what JIRA group they are in).  I managed to get the custom field updating correctly on the ticket but when i try to query against the field nothing comes back - I assume it hasn't been committed to the DB.  Any ideas whats wrong?  As you can see from my code I'm using .updateValue

 

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.Issue

// the name of the custom field (single select list type)
final String customFieldName = "Regional Team"

// the value of the new option to set
final String CSEMEA = "EMEA CS Team"
final String CSNA = "NA CS Team"
final String CSAPAC = "APAC CS Team"
final String NONCS = "Other Teams"

// the issue key to update
final String issueKey = "SUP-33800"

// the user making this update/commit
final String commituser = "JIRA Integration"

def issue = ComponentAccessor.issueManager.getIssueByCurrentKey(issueKey)
def customField = ComponentAccessor.customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
def assignee = issue.getAssignee()
def groupManager = ComponentAccessor.getGroupManager()
def availableOptions = ComponentAccessor.optionsManager.getOptions(customField.getRelevantConfig(issue))

if (assignee != null && groupManager.getUsersInGroup("APAC Team").contains(assignee)) {
def optionToSet = availableOptions.find { it.value == CSAPAC }
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), optionToSet), new DefaultIssueChangeHolder())

}
else if (assignee != null && groupManager.getUsersInGroup("NA Team").contains(assignee)) {
def optionToSet = availableOptions.find { it.value == CSNA }
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), optionToSet), new DefaultIssueChangeHolder())

}
else if (assignee != null && groupManager.getUsersInGroup("EMEA Team").contains(assignee)) {
def optionToSet = availableOptions.find { it.value == CSEMEA }
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), optionToSet), new DefaultIssueChangeHolder())

}
else {
def optionToSet = availableOptions.find { it.value == NONCS }
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), optionToSet), new DefaultIssueChangeHolder())

}
Mike Silverglate February 28, 2020

I am not able to commit to the database.  I have to update my Story or wait a time before the data is available to use for reporting - I am not sure what I am doing wrong?

import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.link.IssueLink
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue

Issue issue = event.issue
if (issue.getIssueType().name == "Epic"){
def customFieldManager = ComponentAccessor.getCustomFieldManager();
def issueLinkManager = ComponentAccessor.getIssueLinkManager()
List<IssueLink> outwardLinks = issueLinkManager.getOutwardLinks(issue.getId())
CustomField cf1 = customFieldManager.getCustomFieldObjectByName("Bundle ID")
def cfvalue = issue.getCustomFieldValue(cf1)

List<Issue> issueinepic = new ArrayList<Issue>();

for(int i=0;i<outwardLinks.size();i++){
if(outwardLinks[i].getIssueLinkType().getName()=="Epic-Story Link"){
def destObject = outwardLinks[i].getDestinationObject()
def changeHolder = new DefaultIssueChangeHolder();
cf1.updateValue(null, destObject, new ModifiedValue(destObject.getCustomFieldValue(cf1),cfvalue), changeHolder)
// issue.store()

}
}
}

Mike Silverglate March 4, 2020

I win!!!!   I added a comment and raised an IssueCommented event - now the reporting works 

 

https://scriptrunner.adaptavist.com/4.3.3/jira/recipes/workflow/postfunctions/append-generate-comment.html

 

 

import com.atlassian.jira.issue.Issue;

import com.atlassian.jira.component.ComponentAccessor;

import com.atlassian.jira.issue.fields.CustomField;

import com.atlassian.jira.issue.link.IssueLink

import com.atlassian.jira.issue.MutableIssue

import com.atlassian.jira.issue.util.DefaultIssueChangeHolder

import com.atlassian.jira.issue.ModifiedValue

 

def issue = event.issue

def commentManager = ComponentAccessor.getCommentManager()

def user = ComponentAccessor.getJiraAuthenticationContext().getUser()

if (issue.getIssueType().name == "Epic"){

def customFieldManager = ComponentAccessor.getCustomFieldManager()

def issueLinkManager = ComponentAccessor.getIssueLinkManager()

List<IssueLink> outwardLinks = issueLinkManager.getOutwardLinks(issue.getId())

CustomField cf1 = customFieldManager.getCustomFieldObjectByName("Bundle ID")

def cfvalue = issue.getCustomFieldValue(cf1)

 

List<Issue> issueinepic = new ArrayList<Issue>();

 

for(int i=0;i<outwardLinks.size();i++){

if(outwardLinks[i].getIssueLinkType().getName()=="Epic-Story Link"){

def destObject = outwardLinks[i].getDestinationObject()

def changeHolder = new DefaultIssueChangeHolder();

cf1.updateValue(null, destObject, new ModifiedValue(destObject.getCustomFieldValue(cf1),cfvalue), changeHolder)

commentManager.create(destObject, user,"Added BundleID"+cfvalue,true)

//destObject.store()

 

}

}

}

0 votes
Daniel Alonso September 25, 2019

Any suggestions to update User Type Fields?

y_r December 12, 2019

I have the same Pb

Vytautas Chamutovskij May 4, 2020

Do you mean update field with user value? Just retreive ApplicationUser object by user name or id and update custom field as descibed above.

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events