Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

How to get and set custom field values via API

Rajeev Gill January 24, 2020

This appears to be a question which has already been asked however the answers I found did not relate to my particular situation.

I am writing a script using the app 'Scriptrunner' which has been installed on an instance of Jira Service Desk Cloud not server. 

I am also writing this script in the context of a 'Post function', the script is triggered upon creation of a new issue

What I am trying to do with the script is:

1. Get the value of the custom field 'Market' from the created issue

2. Depending on the value found in the 'Market' field

3. Create a new custom field on the created issue and populate the value of the new custom field

 

The problem I am having is getting the values of the custom fields (I haven't got as far as setting a new custom field yet.

// Get all the fields from the issue as a Map
def fields = issue.fields as Map

log.debug("FIELDS:" + fields)

 I get the fields by using the above snippet, it should return the following fields:

ticket.pngHowever the log output shows that the majority of the fields have the value 'null', see below:

2020-01-24 14:35:21.237 DEBUG - FIELDS:[customfield_10070:null, customfield_10071:null, customfield_10072:null, customfield_10073:null, customfield_10076:null, customfield_10077:null, customfield_10078:null, resolution:null, customfield_10079:null, lastViewed:null, customfield_10060:null, customfield_10061:null, customfield_10062:null, customfield_10063:null, customfield_10064:null, customfield_10065:null, customfield_10066:https://www.volkswagen.it/it.html, customfield_10067:https://www.volkswagen.it/it.html, customfield_10068:null, labels:[], aggregatetimeoriginalestimate:null, issuelinks:[[id:10280, self:https://vw-engine.atlassian.net/rest/api/2/issueLink/10280, type:[id:10003, name:Relates, inward:relates to, outward:relates to, self:https://vw-engine.atlassian.net/rest/api/2/issueLinkType/10003], outwardIssue:[id:12395, key:ES-485, self:https://vw-engine.atlassian.net/rest/api/2/issue/12395, fields:[summary:OPS - Automation of Jira processes, status:[self:https://vw-engine.atlassian.net/rest/api/2/status/3, description:This issue is being actively worked on at the moment by the assignee., iconUrl:https://vw-engine.atlassian.net/images/icons/statuses/inprogress.png, name:In Progress, id:3, statusCategory:[self:https://vw-engine.atlassian.net/rest/api/2/statuscategory/4, id:4, key:indeterminate, colorName:yellow, name:In Progress]], priority:[self:https://vw-engine.atlassian.net/rest/api/2/priority/3, iconUrl:https://vw-engine.atlassian.net/images/icons/priorities/medium.svg, name:Medium, id:3], issuetype:[self:https://vw-engine.atlassian.net/rest/api/2/issuetype/10006, id:10006, description:A task that needs to be done., iconUrl:https://vw-engine.atlassian.net/secure/viewavatar?size=medium&avatarId=10517&avatarType=issuetype, name:Task, subtask:false, avatarId:10517]]]]], assignee:[self:https://vw-engine.atlassian.net/rest/api/2/user?accountId=5be05eade3a3ee7e0823c2f9, accountId:5be05eade3a3ee7e0823c2f9, avatarUrls:[48x48:https://avatar-management--avatars.us-west-2.prod.public.atl-paas.net/i

As you can see the only custom fields I can get via the API are 'Website/Domain' and 'Page URL example' - Does anybody know how I can access ALL fields?

def issue = get("/rest/api/2/issue/${issueId}")
.header('Content-Type', 'application/json')
.asObject(Map)
.body

Just to add I have used both the above method and the method detailed in my initial question.

Thanks in advance

1 answer

0 votes
Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 24, 2020

Hi Rajeev,

Thank you for your question.

I can confirm the example shown in the ScriptRunner for Jira Cloud documentation site located here shows how to return all of the custom fields in a post function in the customFields rest call located at the top of the script.

This rest API call gets all of the custom field objects and the script shows how to then return values off of fields on the issue.

You will be able to use this script as a reference to see how to get the field values you require inside of your script.

I can also confirm on the documentation pages located here we have examples of how to set the values in different types of fields which you may find helpful.

I hope this information helps.

Regards,

Kristian

Rajeev Gill January 29, 2020

Thanks Kristian!

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 29, 2020

Hi Rajeev,

Thank you for confirming that our response allowed you to achieve your requirements.

Regards,

Kristian

Rajeev Gill January 29, 2020

Hi Kristian,

 

Unfortunately the second part of the suggested script doesn't work.

I am able to get the value of the 'Market' field but I am unable to set the value of the Region field.

When I try to set the value of the region field and then log that value it returns null, see code and log output below:

//Add libsimport org.apache.log4j.Loggerimport org.apache.log4j.Levelimport groovy.json.JsonSlurper
//Set up loggerdef log = Logger.getLogger("Rajeevs log")log.setLevel(Level.DEBUG)
//List nations and associated regions as stringdef nation_info_str = '''[
//A json list of nations (I left it out because it is too long)
]'''
//Convert list of nations into JSON objectdef jsonSlurper = new JsonSlurper()def nations_json = jsonSlurper.parseText(nation_info_str)
//Get custom fieldsdef customFields = get("/rest/api/2/field")        .asObject(List)        .body        .findAll { (it as Map).custom } as List<Map>
//get market custom field IDdef marketId = customFields.find { it.name == 'Market' }?.id
//get region custom field IDdef regionId = customFields.find { it.name == 'Region' }?.id
//get market namedef marketName = issue.fields[marketId]?.value
//Cycle through each nation in listfor (int i = 0; nations_json.length; i++) {    //If nation in list matches market of current ticket    if(nations_json[i]?.name == marketName) {        //Set custom field 'region' of issue to region property in nations list e.g. region = nations[i].region        log.debug("THIS TICKET HAS BEEN SUBMITTED FROM " + nations_json[i]?.region)                put("/rest/api/2/issue/${issue.key}"        // .queryString("overrideScreenSecurity", Boolean.TRUE)         .header("Content-Type""application/json")        .body([            fields:[                    (regionId): nations_json[i]?.region            ]        ])        .asString()            }        break}
customFields = get("/rest/api/2/field")        .asObject(List)        .body        .findAll { (it as Map).custom } as List<Map>
//log.debug("ISSUEKEY" + issue.key)log.debug("REGIONFIELD " + customFields.find { it.name == 'Region' })log.debug("REGIONFIELD " + customFields.find { it.name == 'Region' }?.value)

Log output

2020-01-29 13:58:07.001 INFO - Serializing object into 'interface java.util.List'2020-01-29 13:58:07.012 INFO - GET /rest/api/2/field asObject Request Duration: 540ms2020-01-29 13:58:07.344 INFO - Serializing object into 'interface java.util.List'2020-01-29 13:58:07.350 INFO - GET /rest/api/2/field asObject Request Duration: 299ms2020-01-29 13:58:07.410 DEBUG - REGIONFIELD [id:customfield_10179, key:customfield_10179, name:Region, custom:true, orderable:true, navigable:true, searchable:true, clauseNames:[cf[10179], Region], schema:[type:option, custom:com.atlassian.jira.plugin.system.customfieldtypes:select, customId:10179]]2020-01-29 13:58:07.412 DEBUG - REGIONFIELD null2020-01-29 13:58:07.430 INFO - Condition didn't eval to true, exiting

 

Do you know how to properly set a custom field value?

 

Many thanks,

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 29, 2020

Hi Rajeev,

From your error trace above I see the message of Condition didn't eval to true, exiting, This message indicates that your script did not run as you have a condition configured for it which did not pass.

So that I can advise further on this issue, can I please ask if you can attach a full-page screenshot showing exactly how you have configured your script as I will need this to advise further on why the field is not being set.

Also, can you please confirm what type of field the Region field is so I can advise further on how to set this field, as it looks as if your syntax for setting the Region field may be invalid.

Regards,

Kristian

Rajeev Gill January 29, 2020

Hi Kristian,

 

Here is the full script:

postfunction_script.png

def nation_info_str is a JSON list of nations which, which looks like this:

{        

  "name": "Guatemala",        

  "region": "LATAM"    

},

A few points to note, you will see 'Region2' instead of 'Region' as in this version of the script I am testing a different custom field called 'Region2' 

The 'Region' custom field is a multiple selection drop down box whereas 'Region2' is a simple single line text in put.

I've tried with both input field types with no success so far

Rajeev Gill January 29, 2020

postfunction_script.png

Rajeev Gill January 29, 2020

Full size script image link: https://www.screencast.com/t/mdtb5bboJ

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 29, 2020

Hi Rajeev,

Thank you for your response.

I notice in your script screenshot that you are trying to just pass the JSON as the structure for the filed and this will not be valid for the text field you are setting as the text field requires the value you set to be a String which means you will need to convert the value to a string in order to be able to set it.

Finally, I can confirm we have an example script located here which shows the structure that should be used to set a single select list field which you can use as a reference as I can confirm we do not have an example of how to set a multi-select list field.

Regards,

Kristian

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 29, 2020

Hi Rajeev,

I can confirm I have just created the example code snippet located here and can confirm I have tested this and that when run on the script console this code snippet will populate a multi-select list field on an issue and will be a useful reference to show you how to refactor your script to set the multi-select list field. 

I hope this helps.

Regards,

Kristian

Like Manoj Vutukuri likes this
Rajeev Gill January 31, 2020

Hi Kristian,

 

Thank you for the code snippet, it is much appreciated. 

 

Can you confirm, this code snippet will enable me to update the value of the custom field, at first glance it seems as though it will just update the multi-select options the user can choose from.

 

Thanks!

Rajeev

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 31, 2020

Hi Rajeev,

Thank you for your response.

You are correct the code snippet will only allow you to update with multi-select list options that users can choose from.

This is a limitation of Jir itself as the API mandates that you can specify a valid value which has been configured for the field and will not allow you to set a value which has not been configured for the field.

I understand this response may be frustrating but please understand that this ls a limitation of Jira and ScriptRunner is unable to work around this.

Regards,

Kristian

Rajeev Gill January 31, 2020

Hi Kristian,

As the values APAC, LATAM and EMEA are already configured for the field, would we not be able to set one of those values?

Failing that, would we be able to set a custom field value if we used a different field type?

Many thanks for the support,

Rajeev

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 31, 2020

Hi Rajeev,

I can confirm if those values are values which you can set manually on the screen, then you will be able to set them using the Rest API and using the example provided as an example to ensure you specify the values in the right format that the API call expects.

As for another field type if it is any form of selection fields such as a select list, checkbox or radio buttons etc then you will only be able to set options which exist for the field as Jira mandates this as explained previously.

If you wanted to set a value based on a value defined in your script then you will need to use a text field and pass the value to be set as a String.

I hope this information helps.

Regards,

Kristian

Rajeev Gill January 31, 2020

l

Rajeev Gill January 31, 2020

Kristian,

 

Which example shows how to set a custom field to an already configured option, the code example on bitbucket appears to only add additional custom field options for the user to select.

 

Thanks,

Rajeev

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 31, 2020

Hi Rajeev,

I can confirm the code example I shared which is located here will set the values on a multi-select list field.

I think you are misunderstanding the code as the add syntax is required to tell the rest the API to add one of the valid options available for the field to the selected options as it is a multi-select list field.

The reason for this is that the field may already have an option value selected and you may be selecting another value out of the valid options which exist for the field.

As mentioned previously this code will require you to specify a value which exists as Jira will not allow you to create a new option which is not valid for the field.

Please, note that I have tested this code myself and can confirm that this is a working example and will set the values if you run this on the script console specifying a valid issue, custom field ID and valid option values.

Could I please ask you to try running this code on the script console in your instance in order to see how to to set a value and learn how it works.

Regards,

Kristian

Rajeev Gill January 31, 2020

Hi Kristian,

I have run this script without errors however the 'Region' field remains 'null'

postfunction_script_2.png

This is the log output

2020-01-31 13:13:06.309 INFO - Serializing object into 'interface java.util.List'
2020-01-31 13:13:06.842 INFO - GET /rest/api/2/field asObject Request Duration: 3537ms
2020-01-31 13:13:07.194 INFO - Serializing object into 'interface java.util.List'
2020-01-31 13:13:07.243 INFO - GET /rest/api/2/field asObject Request Duration: 337ms
2020-01-31 13:13:07.283 DEBUG - REGIONFIELD [id:customfield_10179, key:customfield_10179, name:Region, custom:true, orderable:true, navigable:true, searchable:true, clauseNames:[cf[10179], Region], schema:[type:option, custom:com.atlassian.jira.plugin.system.customfieldtypes:select, customId:10179]]
2020-01-31 13:13:07.304 DEBUG - REGIONFIELD null
2020-01-31 13:13:07.322 INFO - Condition didn't eval to true, exiting

 I guess I am not making the API request in the correct format or with the correct parameters?

Thanks again for your support

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 31, 2020

Hi Rajeev,

Looking at your screenshot I see the option you are trying to set is called nations_json[i]?.region and you have this in double-quotes which means you are telling the API to select an option with this name from the drop-down.

To me, this looks invalid as I am guessing you have not configured an option called nations_json[i]?.region.

If your script should be setting this to the value which is defined by this then you should create a new variable of type String which stores this value and you should set the option to this value.

In groovy when you pass a variable you would just pass its name e.g myVariable without having it quoted.

I hope this helps.

Kristian

Rajeev Gill January 31, 2020

Hi Kristian,

I've refactored the code to pass nations_json[i]?.region as a string, see screenshot below:

postfunction_script_3.png

lI am still getting 'Null' when I check the 'Region' value on line 872

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
January 31, 2020

Hi Rajeev,

Thank you for your response.

I can confirm that line 872 as shown in your screenshot appears to be a log statement and I believe the syntax of your log statement is invalid which is why it is logging out null.

I would advise trying to save the value of the field to a variable in your script as a String and then to just log out this variable to see what the value is.

Regards,

Kristian

Rajeev Gill February 3, 2020

Hi Kristian,

Thank you for all of your help.

Unfortunately I am new to Groovy, this is the first time I have ever used it. Could you show me the correct way to log out the value of 'Region'?

I also checked the ticket I am using to test and can see that the 'Region' field is still null, see picture below:

region_field.png

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
February 5, 2020

Hi Rajeev,

I notice from your screenshot that the Region Field does not have a value, can you please confirm if this is from after you have run the script to set the value?

If this is the case from after you have set the value, then this shows that your logic is invalid as the value has not been set from your script and I would advise trying to hardcode setting a value in the field to test if your logic for your rest API call to set the region call is valid.

Regards,

Kristian

Rajeev Gill February 12, 2020

Hey Kristian,

I've refactored the code to include only the API call:

2020-12-02_1206_1206PM.png

and I get the following error:

WARN - PUT request to /rest/api/2/issue/EN-1841 returned an error code: status: 400 - Bad Request
body: {"errorMessages":["Field with id' customfield_10179' and name 'Region' does not support operation 'add' Supported operation(s) are: 'set'"],"errors":{}}

BTW 'add' was unsupported action on a multiselect field so I used 'set' instead.

 

Do you know if there is any type of custom field that can be set automatically?

 

Thanks,

Rajeev 

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
February 13, 2020

Hi Rajeev,

I can confirm that it is possible to set fields automatically with ScriptRunner for Jira Cloud and that if you are getting an error that it means that the syntax of your rest call is invalid.

I can confirm that as you have said the Region field is a multi select list field that the syntax to use to set a multi select list field can be viewed in the example here.

I can confirm that I have tested this example and can confirm that using this I was able to update the values on a Multi Select List field in my instance in order to verify that this syntax is correct and valid.

Regards,

Kristian

Rajeev Gill February 13, 2020

Hi Kristian,

 

I am using the exact same syntax (copied and pasted from your example) and still get pretty much the same error:

2020-02-13_1542.png

WARN - PUT request to /rest/api/2/issue/EN-1841 returned an error code: status: 400 - Bad Request
body: {"errorMessages":["Field with id' customfield_10179' and name 'Region' does not support operation 'add' Supported operation(s) are: 'set'","Field with id' customfield_10179' and name 'Region' does not support operation 'add' Supported operation(s) are: 'set'"],"errors":{}}

Using both 'add' and 'set' appear not to work.

I wonder is it easier to use a different custom field type?

Thanks,

Rajeev

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
February 13, 2020

Hi Rajeev,

Can you please confirm that the Region field is of the type Select List (multiple choices) as this is the type of field that this example is designed to work for.

Also can you please confirm that the Field contains two options called test and test2 configured for it which can be set manually on the issue as you can only set options which have been configured for the field when using the API.

If you wanted to use a simpler field type you could try getting the value and saving it as a String and then updating a text field which would be similar to how the summary is set in the example here.

Finally, Can I confirm how are you running this code is it with the ScriptRunner for Jira Cloud plugin or with another plugin?

I hope this helps.

Regards,

Kristian

Rajeev Gill February 13, 2020

Hi Kristian,

 

I can confirm the first two points, will try with a text field.

 

Thanks,

Rajeev

Rajeev Gill February 13, 2020

Hi Kristian,

 

I have tried using both examples to set 'Region' (MultiSelect) and 'Region2' (Text field)

2020-02-13_1709_TF.png

The above code returns this error: 

WARN - PUT request to /rest/api/2/issue/EN-1841 returned an error code: status: 400 - Bad Request
body: {"errorMessages":[],"errors":{"Region2":"Field 'Region2' cannot be set. It is not on the appropriate screen, or unknown."}}

 

The field 'Region2' has been added to every screen we have...

2020-02-13_1709_TF2.pngDo you have any idea how to get past this error?

 

thanks,

Rajeev 

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
February 13, 2020

Hi Rajeev,

Thank you for your response.

Can I please confirm if you have tried running the script as the ScriptRunner Add On User to see if this resolves your issue as you must run the ScriptRunner Add On User when you specify the overrideScreenSecurity queryString paramater inside of your rest call. 

Also can I please ask that the context for the field defines that it is available for the issue type that your issue is using?

Regards,

Kristian

Rajeev Gill February 13, 2020

Hi Kristian,

 

I can confirm that script is running as ScriptRunner Add On User and can confirm that I am using the line .queryString("overrideScreenSecurity", Boolean.TRUE)

 

I can also confirm that this field can be used on all issues:

2020-02-13_1722.png

thank you!

Rajeev

Kristian Walker _Adaptavist_
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
February 13, 2020

Hi Rajeev,

Looking at your script I notice you are specifying the name of the field as Region2 but the API will require this field to be specified by its ID so can you specify by its custom field ID to see if this resolves the issue which you are seeing.

Regards,

Kristian

Biswajeet October 12, 2020

Hi Kristian,

There is a similar kind of requirement which we are trying to achieve can you please help here.

We have a Issue Type called "Resource" in JIRA. The Resource Issue type give the details of the personal information of a User or a employee of a organization.

We need a way where we can just fill in the enterprise id or email id of  Resource and the remaining details gets populated automatically in the JIRA form. Is there any way to achieve this, if yes then kindly help use here.

Can we configure the Rest API of our database where all the information of the employee is stored ? If yes, then where can we do that and how can we achieve this.

We are able to fetch those data from the rest api via postman.

Regards

Biswajeet

shiva May 3, 2021

Hi Kristin,

I need suggestions regarding api user map to custom field... 

Is their is an alternate for api users to map jira custom field instead of name and id?

With any other custom field properties or coding...

Thank and Regards

Shiv

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events