How to update customfield value [scriptrunner]

xion_admin May 27, 2016

I have following scripts where I use `issue.setCustomFieldValue`, however, the data will not be stored when I look into the issue. What is wrong or missing here?

 

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.search.SearchProvider
import com.atlassian.jira.jql.parser.JqlQueryParser
import com.atlassian.jira.web.bean.PagerFilter
import com.atlassian.jira.user.util.DefaultUserManager
import com.atlassian.crowd.embedded.api.User

import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()
def userManager = ComponentAccessor.getUserManager();
def user = userManager.getUser('user');

// edit this query to suit
def query = jqlQueryParser.parseQuery('project = DIV')

def results = searchProvider.search(query, user, PagerFilter.getUnlimitedFilter())


CustomFieldManager customFieldManager = ComponentAccessor.getCustomFieldManager()

  
CustomField customFieldEnv = customFieldManager.getCustomFieldObjectByName( "Environment" );
CustomField customFieldArch = customFieldManager.getCustomFieldObjectByName( "Architecture" );
CustomField customFieldOS = customFieldManager.getCustomFieldObjectByName( "OS" );

def result=[];
results.getIssues().each {tmpIssue ->

    def issue = issueManager.getIssueObject(tmpIssue.id)
    def value = issue.getCustomFieldValue( customFieldEnv ).toString()
    def newValue=[];

    if (value.contains("x86"))
       newValue.add("x86")
     if (value.contains("64"))
        newValue.add("x64")
        
    if (newValue.size() > 0)
    {
        result.add(issue)
        issue.setCustomFieldValue( customFieldArch, newValue )
    }
}

return result;

3 answers

1 accepted

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

4 votes
Answer accepted
adammarkham
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.
May 30, 2016

Its because its not getting stored in the database or reindexed.

When updating an issue, its nearly always best to use IssueService as thats what JIRA uses underneath to update issues which persists the update and does the reindexing for you.

You should be able to adapt the code below to set the selected values in the select list:

import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.IssueInputParameters
import com.atlassian.jira.issue.customfields.manager.OptionsManager
import com.atlassian.jira.issue.customfields.option.Options

IssueService issueService = ComponentAccessor.getComponent(IssueService);
def customFieldManager = ComponentAccessor.getComponent(CustomFieldManager);
def optionsManager = ComponentAccessor.getComponent(OptionsManager);
IssueInputParameters issueInputParameters = issueService.newIssueInputParameters()

def user = ComponentAccessor.getJiraAuthenticationContext().loggedInUser
def issue = issueService.getIssue(user, "SSPA-15")?.issue

def customField = customFieldManager.getCustomFieldObjectByName("SelectListA")

Options options = optionsManager.getOptions(customField.getConfigurationSchemes().first().getOneAndOnlyConfig());

def selectedOptions = options.findAll {
    it.value == "AAA"
}.collect {
    it.optionId.toString()
}

// Setting none will work if it can't find an option
issueInputParameters.addCustomFieldValue(customField.id, *selectedOptions)

def update = issueService.validateUpdate(user, issue.id, issueInputParameters)
if (update.isValid()) {
    issueService.update(user, update)
}

To select checkbox values you should use:

import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.IssueInputParameters
import com.atlassian.jira.issue.customfields.manager.OptionsManager
import com.atlassian.jira.issue.customfields.option.Options

IssueService issueService = ComponentAccessor.getComponent(IssueService);
def customFieldManager = ComponentAccessor.getComponent(CustomFieldManager);
def optionsManager = ComponentAccessor.getComponent(OptionsManager);
IssueInputParameters issueInputParameters = issueService.newIssueInputParameters()

def user = ComponentAccessor.getJiraAuthenticationContext().loggedInUser
def issue = issueService.getIssue(user, "SSPA-15")?.issue

def customField = customFieldManager.getCustomFieldObjectByName("Checkboxes")

Options options = optionsManager.getOptions(customField.getConfigurationSchemes().first().getOneAndOnlyConfig());

def selectedOptions = options.findAll {
    it.value == "Yes" || it.value == "Maybe"
}.collect {
    it.optionId.toString()
}

issueInputParameters.addCustomFieldValue(customField.id, *selectedOptions)

def update = issueService.validateUpdate(user, issue.id, issueInputParameters)
if (update.isValid()) {
    issueService.update(user, update)
}
Royce Wong
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.
July 26, 2016

Hi @Adam Markham [Adaptavist],

Thanks for the code. In your 'Checkboxes' example, does it infer you have a check box field named 'Checkboxes' with two options:

  • Yes
  • Maybe

? Because I don't quite follow this part of the code:

def selectedOptions = options.findAll {
    it.value == "Yes" || it.value == "Maybe"
}.collect {
    it.optionId.toString()
}

What is the variable 'it'?

I tried your code in script console but it didn't select my checkbox's values, but no error was thrown. What could be wrong? I am running JIRA 6.2.2, ScriptRunner 3.0.16.

In addition, the example code on https://scriptrunner.adaptavist.com/latest/jira/recipes/behaviours/setting-default-fields.html#_setting_defaults_for_selects_etc looks different but seems to update checkbox field as well? Please consider updating that documentation if necessary.

Thanks in advance.

 

adammarkham
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.
July 26, 2016

Hi, did you change the issue key, my one was "SSPA-15" you need to replace that with your specific issue key.

The variable "it" is just an implicit parameter in the closure: http://groovy-lang.org/closures.html#implicit-it
H
ere it is just your option.

It could have been written like:

def selectedOptions = options.findAll { option ->
    option.value == "Yes" || option.value == "Maybe"
}.collect {
    option.optionId.toString()
}

Yes it will look through all the options you have and will check them if they are "Yes" or "Maybe". You should replace these with your options. Once you have addressed these things its likely to work.

Do you see any errors in the script console or it just doesn't work?

Royce Wong
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.
July 27, 2016

Hi @Adam Markham [Adaptavist],

I did update the issue key. I did more testing and I found that:

Case 1) If options were checked, the code will uncheck them.

Case 2) If options were unchecked, the code WON'T check them.

I don't see any errors in script console.

My checkbox field is named: "Issue Flags" which has two options:

  1. SLA Response Not Meet
  2. SLA Resolution Not Meet

So my code looks like

def selectedOptions = options.findAll {
    it.value == "SLA Response Not Meet" || it.value == "SLA Resolution Not Meet"
}.collect {
    it.optionId.toString()
}

Any insights why the code won't check the options? Thanks again in advance.

adammarkham
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.
July 28, 2016

Ok I have just tested this again and it seems to work for me. Just to clarify I have checkbox options "Yes", "No" and "Maybe".

The code I supplied will check "Yes" and "No" and leaved "Maybe" unchecked.

To check just "SLA Response Not Meet" you need:

def selectedOptions = options.findAll {
    it.value == "SLA Response Not Meet"
}.collect {
    it.optionId.toString()
}

I'm not sure why you are seeing the behaviour you have described. I assume you replaced:

def customField = customFieldManager.getCustomFieldObjectByName("Checkboxes")

with the name of your checkbox "Issue Flags"?

What version of ScriptRunner and JIRA are you using?

Royce Wong
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.
July 28, 2016

Hi @Adam Markham [Adaptavist],

Thanks for testing again. Yes, I replaced "Checkboxes" with "Issue Flags".

"The code I supplied will check "Yes" and "No" and leaved "Maybe" unchecked." Did you mean the code you supplied will check "Yes" and "Maybe" and leaved "No" unchecked.

I am running JIRA 6.2.2, ScriptRunner 3.0.16.

Royce Wong
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 10, 2016

Hi @Adam Markham [Adaptavist],

I think I found out what the issue was, it has to to with this line:

Options options = optionsManager.getOptions(customField.getConfigurationSchemes().first().getOneAndOnlyConfig());

It is assuming we are dealing with the custom field's FIRST configuration scheme. But I have multiple config. schemes for my custom field "Issue Flags" and my options ("SLA Response Not Meet") does not belong to the first configuration scheme. Now I think I have to figure out how to get specific config. scheme, or do you know how?

Thanks.

 

adammarkham
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 11, 2016

Ah, yeah its getting the first one. You can find the config scheme like so by name:

def fieldConfig = customField.getConfigurationSchemes().find {
    it.name == "My Scheme"
}.getOneAndOnlyConfig()

Also it.id == 12345 will work if you know the id.

2 votes
Mayur Supare May 30, 2016

Hi,

you can use this code to update value for custom field

Map<String, ModifiedValue> modifiedFields = myIssue.getModifiedFields();
DefaultIssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();

myIssue.setCustomFieldValue(initial_response,minute);

FieldLayoutItem fieldLayoutItem= ComponentAccessor.getFieldLayoutManager().getFieldLayout(myIssue).getFieldLayoutItem(initial_response);

final ModifiedValue modifiedValue = (ModifiedValue) modifiedFields.get(initial_response.getId());

initial_response.updateValue(fieldLayoutItem, myIssue, modifiedValue, issueChangeHolder);

in this code,

initial_response is a custum field and minute is a value.

minute is set to a initial_response custom field 

0 votes
Jeremy Gaudet
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.
May 27, 2016

You need to follow up with IssueManager.updateIssue().  Example:

issueManager.updateIssue(user, issue, EventDispatchOption.ISSUE_UPDATED, false);
xion_admin May 29, 2016

When I call this function, I get following message:

Error
java.lang.String cannot be cast to com.atlassian.jira.issue.customfields.option.Option
java.lang.ClassCastException: java.lang.String cannot be cast to com.atlassian.jira.issue.customfields.option.Option
    at com.atlassian.jira.issue.customfields.impl.MultiSelectCFType.convertTypeToDbValue(MultiSelectCFType.java:82)
    at com.atlassian.jira.issue.customfields.impl.AbstractMultiCFType.convertTypesToDbObjects(AbstractMultiCFType.java:190)
    at com.atlassian.jira.issue.customfields.impl.AbstractMultiCFType.updateValue(AbstractMultiCFType.java:142)
    at com.atlassian.jira.issue.customfields.impl.AbstractMultiCFType.updateValue(AbstractMultiCFType.java:39)
    at com.atlassian.jira.issue.fields.CustomFieldImpl.updateValue(CustomFieldImpl.java:462)
    at com.atlassian.jira.issue.fields.CustomFieldImpl.updateValue(CustomFieldImpl.java:432)
    at com.atlassian.jira.issue.managers.DefaultIssueManager.updateFieldValues(DefaultIssueManager.java:704)
    at com.atlassian.jira.issue.managers.DefaultIssueManager.updateIssue(DefaultIssueManager.java:669)
    at com.atlassian.jira.issue.managers.DefaultIssueManager.updateIssue(DefaultIssueManager.java:655)
    at com.atlassian.jira.issue.IssueManager$updateIssue$0.call(Unknown Source)
    at Script671$_run_closure1.doCall(Script671.groovy:51)
    at Script671.run(Script671.groovy:34)
xion_admin May 29, 2016

My custom field is a single list, where multiple values are allowed.

Jeremy Gaudet
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.
May 30, 2016

I think the issue is that you can't add a String, you have to add an Option. Adam's response above shows some examples of how to get the Option based on the string.

adammarkham
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.
May 31, 2016

Yes you need to set the value as an Option rather than a String. 

TAGS
AUG Leaders

Atlassian Community Events