It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

How to update customfield value [scriptrunner]

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

3 votes
Answer accepted

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)
}

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.

 

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?

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.

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?

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.

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.

 

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.

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 

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

issueManager.updateIssue(user, issue, EventDispatchOption.ISSUE_UPDATED, false);

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)

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

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.

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

Suggest an answer

Log in or Sign up to answer
This widget could not be displayed.
This widget could not be displayed.
Community showcase
Posted 3 hours ago in Jira

Upcoming Enterprise releases targeting Q3 2019: Jira Software 8.5 & Jira Service Desk 4.5

Since launching the Jira Software 8.0 and Jira Service Desk 4.0 platform releases in February, many of you have been asking when the next Enterprise release will be so you can take advantage of the m...

162 views 0 3
Join discussion

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