Copy Field Value to Custom Field During Workflow Transition (Quick Bite)

Imagine you have a Jira Service Management issue with a component.  That component has a component lead, i.e. a person designated as the person responsible for that component. 

When the issue transitions, you want the workflow to add the component lead to a separate user picker custom field.  In effect, we’re copying a user from one field and adding it to another, likely for the purposes of oversight or reporting.

A ScriptRunner custom script postfunction is added to the workflow transition. The code itself isn’t terribly complicated, so long as the context is understood.   That is, we first need to understand that for a transition, the system knows that “issue” will represent the issue at the time of execution.   This is different than hard-coding the script, wherein there is no context to provide an issue object.

Please note that this only applies to Jira Cloud.  The code provided won’t work on Jira DC.

All that being said, there are a few steps:

  1. Fetch the issue object
  2. From the issue object, fetch the list of components
  3. Iterate through the components
  4. For each component, return the user ID of the component lead
  5. Use that user id to populate a user picker custom field

Worth noting is that the script will iterate through all of the components, and use the component lead of the final component in the list.  Some filtering or indexing would be required, were a specific component be the target.

 

Here’s the code. Don’t forget to fill in your own custom field ID in the JSON payload.

def get_issue = get("/rest/api/2/issue/${issue.key}")
    .asJson()
//Fetch the issue
def component_info = get_issue.body.jsonObject.fields.components
//Get the components associated with the issue
component_info.each { component ->
//Iterate through the components on the issue
    def get_component = get("/rest/api/2/component/${component.id.toString()}")
        .asJson()
    //Fetch the component details
    def update_cf = put("/rest/api/2/issue/${issue.key}")
    //Update the user_picker custom field with the component lead
        .header("Content-Type", "application/json")
        .body([
            fields: [
                customfield_<customfield id>: [
                    accountId: get_component.body.jsonObject.lead.accountId.toString()
                ]
            ]
        ])
        .asJson()
    if (update_cf.status == 200 || update_cf.status == 204) {
        //Check the result to determine if it was successful
        logger.info("Custom field updated successfully.")
    } else {
        logger.error("Failed to update custom field. Status: ${update_cf.status}")
        logger.error("Response: ${update_cf.body}")
    }
}

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *