Forums

Articles
Create
cancel
Showing results for 
Search instead for 
Did you mean: 

Script Runner - update custom field based on Reporter

Humberto Gomes
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 7, 2023 edited
This is the beginning of my next challenge.
I need help with a (small and simple )script runner code.
The idea is to populate a custom field (number) according to the reporter's information.
Something like:
If reporter = A@mail.com
 Custom field  = 1
 
Else if reporter = B@mail.com
 Custom field  = 1.3
 
Ese if reporter = C@mail.com
 Custom field  = 2.23
 
(...)
Probably the best option is to use a while/switch:
def reporter = issue.getReporter()
switch (reporter) {
   case 'A@mail.com': Custom field  = 1 break
   case 'B@mail.com': Custom field  = 1.3 break
   case 'C@mail.com': Custom field  = 2.23 break
Yes, I know this is a very simple script, but I'm starting with this, so I need your expertise.
Thanks in advance.
 
 

5 answers

2 accepted

1 vote
Answer accepted
Markus W_ BENES
Contributor
August 8, 2023

@Humberto Gomes the failure lies definitifely within variable declaration; but i think the code of @Ram Kumar Aravindakshan _Adaptavist_ should be working; its operating with double :)

Ram Kumar Aravindakshan _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.
August 8, 2023

@Markus W_ BENES

You only have to use the Suggest an Answer field once, i.e. the first time. :-)

All subsequent answers you can provide in the Reply field.

Markus W_ BENES
Contributor
August 8, 2023

@Ram Kumar Aravindakshan _Adaptavist_ Got it now! Thank you :D

1 vote
Answer accepted
Ram Kumar Aravindakshan _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.
August 7, 2023 edited

Hi @Humberto Gomes

For your requirement, you must create a Server-Side Behaviour for the Reporter field.

Below is a working sample code for your reference:-

import com.onresolve.jira.groovy.user.FieldBehaviours
import groovy.transform.BaseScript

@BaseScript FieldBehaviours behaviours
def reporter = getFieldById(fieldChanged)
def reporterValue = reporter.value.toString()

def sampleNumber = getFieldByName('Sample Number')
def value = null

if (reporterValue) {

if (reporterValue == 'admin') {
value = '1.5'
} else if (reporterValue == 'ram') {
value = '2.5'
}

}

sampleNumber.setFormValue(value)

Please note that the sample working code above is not 100% exact to your environment. Hence, you will need to modify it accordingly.

The code above gets the value from the Reporter field, which returns the Reporter's Username as a String.

The Reporter Username is then compared in the if/else statement to identify if the correct reporter is selected. If yes, the Number field will update the value accordingly. Else, the Number field will be empty.

Below is a screenshot of the Server-Side Behaviour configuration:-

behaviour_configuration.png

As an alternative, if you want to search for the user by email address, you can use the coding approach below, it will work the same as the approach provided above.

import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.jira.groovy.user.FieldBehaviours
import groovy.transform.BaseScript

@BaseScript FieldBehaviours behaviours
def reporter = getFieldById(fieldChanged)
def userManager = ComponentAccessor.userManager
def reporterValue = userManager.getUserByName(reporter.value)

def sampleNumber = getFieldByName('Sample Number')
def value = null

if (reporterValue && reporterValue.emailAddress) {

// modify the email addresses accordingly
if (reporterValue.emailAddress == 'user1@mail.com') {
value = '1.5'
} else if (reporterValue.emailAddress == 'user2@mail.com') {
value = '2.5'
}
}
sampleNumber.setFormValue(value)

I am also including a couple of test screenshots for your reference:-

1. When a new issue is created, if the user Reporter is set to the user Admin (username is admin), the Sample Number screen is set to the value 1.5.

test1.png

2. If the user is changed to Ram Kumar (username is ram), as expected, the Sample Number field is updated once again, and the value is changed to 2.5 as shown in the screenshot below:-

test2.png

I hope this helps to solve your question. :-)

Thank you and Kind regards,
Ram

Markus W_ BENES
Contributor
August 7, 2023

@Ram Kumar Aravindakshan _Adaptavist_ Hello why my answer got deleted?

Ram Kumar Aravindakshan _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.
August 7, 2023 edited

Hi @Markus W_ BENES

I'm not sure. I only added my answer above. At that time there was no other response even after refreshing the page.

No idea what happened after that. When did you add your response?

Thank you and Kind regards,

Ram

Markus W_ BENES
Contributor
August 7, 2023

@Humberto Gomes here my answer once again; however it got deleted what i think is not okay; maybe its also of help; 

 

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.Issue

// Key of the Issue that should be changed
def toChangeIssue = "IT-12345" // for actual event -> issue.getKey()

////// Customfields (CF_) //////
def toChangeIssueCustomFields = ["Customfield_12345"] // for no change [""] else [["Customfield_12345", "Last Customfield_23456"]] and so on
def toChangeIssueCustomFieldsValues = [""] // for no change [] else [["Value 1", "Value 2"]] and so on
def toChangeIssueCustomFieldsCheckReporter = true // true or false if set then switch below is working

// search for Issue by Key
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject(toChangeIssue)

// if issue exist then
if(issue){

    // run through customfield Array
    if(toChangeIssueCustomFields.size() > 0 && toChangeIssueCustomFields[0] != "") {

        if(toChangeIssueCustomFieldsCheckReporter == true) {

            // get Issue Reporter
            def reporter = issue.getReporter()
            def reporterName = reporter.getName()

            switch(reporterName) {      
               
                case "A@mail.com":
                    toChangeIssueCustomFieldsValues = ["1"]
                    break;
                case "B@mail.com":
                    toChangeIssueCustomFieldsValues = ["1.2"]  
                    break;
                case "C@mail.com":
                    toChangeIssueCustomFieldsValues = ["2.23"]
                    break;  
                default:
                    toChangeIssueCustomFieldsValues = [""]  
                    break;

            }
       
        }

        // for each vustomfield in array
        toChangeIssueCustomFields.eachWithIndex{ item, index ->

        // search field
        def customFieldManager = ComponentAccessor.getCustomFieldManager()
        def Object cField

        // check if custom field is defined by complete name or ID
        if (toChangeIssueCustomFields[index].toLowerCase().contains("customfield") == true) {
            cField = customFieldManager.getCustomFieldObject(toChangeIssueCustomFields[index].toLowerCase());
        } else {
            cField = customFieldManager.getCustomFieldObjectByName(toChangeIssueCustomFields[index])        
        }

        def cFieldValue = issue.getCustomFieldValue(cField)

        def tgtField = cField
        def changeHolder = new DefaultIssueChangeHolder()
       
        // set new value
        tgtField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(tgtField), toChangeIssueCustomFieldsValues[index]),changeHolder)    
       
        }

    }

    return true

// if issue doesnt exist  
} else {
   
    return false
}
Markus W_ BENES
Contributor
August 7, 2023 edited

@Ram Kumar Aravindakshan _Adaptavist_ after i clicked answer was already here; after some seconds it was away again and your answer was there... looked for me like it got deleted...

my answer was definitely successfully posted because i got 200 kudos and two bageds for it. 

Ram Kumar Aravindakshan _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.
August 7, 2023

@Markus W_ BENES  seems a bit weird. But anyway, as long as your answer is there now.

Markus W_ BENES
Contributor
August 7, 2023 edited

badged.png


@Ram Kumar Aravindakshan _Adaptavist_ if my answer really got not deleted it must have been a bug... here is the screenshot of my badges.

Ram Kumar Aravindakshan _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.
August 7, 2023

@Markus W_ BENES, to be honest, this site is a bit buggy. So the most common issue is the timeout. If you don't respond within 10, you will need to resend the response once again, as the session will timeout. But in your case would be good to report a bug to Atlassian to further investigate.

Markus W_ BENES
Contributor
August 7, 2023

@Ram Kumar Aravindakshan _Adaptavist_ Ok, np; thank you for the info :)

Humberto Gomes
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 8, 2023

Hi @Ram Kumar Aravindakshan _Adaptavist_ 

I extend my gratitude for your prompt response.

Indeed, there seems to be a potential gap in my initial inquiry. Regrettably, the objective cannot be achieved through behaviors. The intention is to implement this either as a Jira automation rule triggered upon ticket creation or as a workflow post-function.

In the interim, I have attempted to apply your provided code to assess its functionality. However, it appears to be non-operational at this point, requiring further refinement. I plan to revisit this matter for testing purposes, with the goal of achieving functionality.

It is crucial for me to execute the script subsequent to the user's creation of the issue. Notably, the information for the value and reporter will not be available on the creation screen.

I am open to alternative suggestions you might have on this matter.

Thank you for your assistance in advance.

Best regards,

Humberto

Ram Kumar Aravindakshan _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.
August 8, 2023 edited

Hi @Humberto Gomes

Thank you for getting back and providing your clarification.

Could you please provide me with a screenshot of the Automation plan you are using so I can try to test it in my environment and provide a solution?

I am looking forward to your feedback.

Thank you and Kind regards,

Ram

Humberto Gomes
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 8, 2023

@Markus W_ BENES 

 

I appreciate your proposed script, acknowledging that it's a community contribution. One initial question arises: why are we using "arrays" in our solution? I apologize for seeking clarification on this matter. Is there a possibility that we're inadvertently overcomplicating the solution?

My perspective was a more direct and simplified code approach. However, I am relying on your expertise and generosity to guide me through this process.

I've made an attempt to integrate your code into an automation rule, but as of now, the functionality remains elusive. The encountered error message reads as follows:

Execute a ScriptRunner script action for Automation for Jira
Script function failed on Automation for Jira rule:
Script function failed on Automation for Jira rule: Hourly Value, file: <inline script>, error: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Double (java.lang.String and java.lang.Double are in module java.base of loader 'bootstrap')

Given this obstacle, I am receptive to exploring alternative suggestions you might offer to address this issue.

I extend my gratitude for your forthcoming assistance.

Best regards,
Humberto

Humberto Gomes
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 8, 2023

@Ram Kumar Aravindakshan _Adaptavist_ 

 

this is what I have now... 

 

Trigger: Issue created.

Action:Run Script Runner

Code:

 

import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.user.ApplicationUser

def customFieldId = "customfield_14400" // Replace this with the actual custom field ID

// Get the current issue
def issue = event.issue as MutableIssue

// Get the reporter's email
def reporterEmail = issue.reporter?.emailAddress

// Define the custom field values based on the reporter's email
def customFieldValue = 0.0 // Default value

if (reporterEmail == "Humberto@mail.com") {
customFieldValue = 12.0
} else if (reporterEmail == "Bernardo@mail.com") {
customFieldValue = 16.5
} else if (reporterEmail == "Hugo@mail.com") {
customFieldValue = 12.5
}
// Add here all conditions for other reporter emails

// Set the custom field value
// ?? how to do it ?? custom field = customFieldValue

Ram Kumar Aravindakshan _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.
August 8, 2023

Hi @Humberto Gomes

In your previous comment, you mentioned:-

I appreciate your proposed script, acknowledging that it's a community contribution. One initial question arises: why are we using "arrays" in our solution? I apologize for seeking clarification on this matter. Is there a possibility that we're inadvertently overcomplicating the solution?

My perspective was a more direct and simplified code approach. However, I am relying on your expertise and generosity to guide me through this process.

I've made an attempt to integrate your code into an automation rule, but as of now, the functionality remains elusive. The encountered error message reads as follows:

Execute a ScriptRunner script action for Automation for Jira
Script function failed on Automation for Jira rule:
Script function failed on Automation for Jira rule: Hourly Value, file: <inline script>, error: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Double (java.lang.String and java.lang.Double are in module java.base of loader 'bootstrap')

The example codes that I have provided are meant for ScriptRunner's Behaviour. It will not work with Automation.

This is why I have asked you for a screenshot of your automation config for example:-

example.png

This is so I can try to test it in my environment and provide a better solution for your requirement.

Thank you and Kind regards,

Ram

Humberto Gomes
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 8, 2023

that was the script shared by @Markus W_ BENES 

 

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.Issue

// Key of the Issue that should be changed
def toChangeIssue = issue.getKey()

////// Customfields (CF_) //////
def toChangeIssueCustomFields = ["Customfield_14400"] // for no change [""] else [["Customfield_12345", "Last Customfield_23456"]] and so on
def toChangeIssueCustomFieldsValues = [""] // for no change [] else [["Value 1", "Value 2"]] and so on
def toChangeIssueCustomFieldsCheckReporter = true // true or false if set then switch below is working

// search for Issue by Key
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject(toChangeIssue)

// if issue exist then
if(issue){

    // run through customfield Array
    if(toChangeIssueCustomFields.size() > 0 && toChangeIssueCustomFields[0] != "") {

        if(toChangeIssueCustomFieldsCheckReporter == true) {

            // get Issue Reporter
            def reporter = issue.getReporter()
            def reporterName = reporter.getName()

            switch(reporterName) {      
               
                case "humberto@mail.com":
                    toChangeIssueCustomFieldsValues = ["1"]
                    break;
                case "bernardo@mail.com":
                    toChangeIssueCustomFieldsValues = ["1.2"]  
                    break;
                case "rui@mail.com":
                    toChangeIssueCustomFieldsValues = ["2.23"]
                    break;  
                default:
                    toChangeIssueCustomFieldsValues = [""]  
                    break;

            }
       
        }

        // for each vustomfield in array
        toChangeIssueCustomFields.eachWithIndex{ item, index ->

        // search field
        def customFieldManager = ComponentAccessor.getCustomFieldManager()
        def Object cField

        // check if custom field is defined by complete name or ID
        if (toChangeIssueCustomFields[index].toLowerCase().contains("customfield") == true) {
            cField = customFieldManager.getCustomFieldObject(toChangeIssueCustomFields[index].toLowerCase());
        } else {
            cField = customFieldManager.getCustomFieldObjectByName(toChangeIssueCustomFields[index])        
        }

        def cFieldValue = issue.getCustomFieldValue(cField)

        def tgtField = cField
        def changeHolder = new DefaultIssueChangeHolder()
       
        // set new value
        tgtField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(tgtField), toChangeIssueCustomFieldsValues[index]),changeHolder)    
       
        }

    }

    return true

// if issue doesnt exist  
} else {
   
    return false
}
Markus W_ BENES
Contributor
August 8, 2023 edited

@Humberto Gomes thank you for your response; i appreciate to help if can but have to say iam a professional programmer but not in groovy/scriptrunner; the code that i posted was intended to be just a beginning for you that should fit as good as it can to your needs but didnt intent to be perfect.

The reason why there are arrays in my code is because i myself need them very very often and therefore prefer them to integrate them from the very beginning in my scripts to be able to make easy loops and multiple edits afterwards. If i really dont need them i remove them from the backuped code as for the special case needed. My intention was to give you a first example, that you can overwork and perfect and fit to your needs as i do it on my own. As you can see the script can either update multiple customfields because of the arrays. If you dont need that just simply remove it, make it therefore faster and easier and just fit it to your needs.

In respond to the failure; i have tested the script again on our system and dont get any error. Is it possible that you didnt change the variables correct? To make it work you need to give an correct issue key and fill out the customfield you want to change. For every running event in an automation you need to change the value to issue.getKey(). The Id of an custom field you can find out easily by going in the Administraion -> Custom Fields and look at the url when you hover over the links like screens or projects. The failure is saying you are mixing variable types. The array variables intend to be stings; so you have to set also numbers into "" like "1.2". The reason why i used strings is because in most cases customfields are textfields or reference fields. Afterwards a simplified version of the code:

 

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.Issue

// Key of the Issue that should be changed
def toChangeIssue = "IT-12345" // for actual event -> issue.getKey()
def toChangeIssueCustomFields = "Customfield_12345"

// search for Issue by Key
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject(toChangeIssue)

// if issue exist then
if(issue){

// get Issue Reporter
def reporter = issue.getReporter()
def reporterName = reporter.getName()
String toChangeIssueCustomFieldsValues = "" // Definition of Variable as String

switch(reporterName) {

case "A@mail.com":
toChangeIssueCustomFieldsValues = "1"
break;
case "B@mail.com":
toChangeIssueCustomFieldsValues = "2"
break;
case "C@mail.com":
toChangeIssueCustomFieldsValues = "3"
break;
default:
toChangeIssueCustomFieldsValues = "4"
break;

}

// search field
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def Object cField

// check if custom field is defined by complete name or ID
if (toChangeIssueCustomFields.toLowerCase().contains("customfield") == true) {
cField = customFieldManager.getCustomFieldObject(toChangeIssueCustomFields.toLowerCase());
} else {
cField = customFieldManager.getCustomFieldObjectByName(toChangeIssueCustomFields)
}

def cFieldValue = issue.getCustomFieldValue(cField)

def tgtField = cField
def changeHolder = new DefaultIssueChangeHolder()

// set new value
tgtField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(tgtField), toChangeIssueCustomFieldsValues),changeHolder)

return true

// if issue doesnt exist
} else {

return false
}

Humberto Gomes
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 8, 2023

I have changed here:

// Key of the Issue that should be changed
def toChangeIssue = issue.getKey()

////// Customfields (CF_) //////
def toChangeIssueCustomFields = ["Customfield_14400"] // for no change [""] else [["Customfield_12345", "Last Customfield_23456"]] and so on
No more changes done.
My Custom field is a number.
This number will be used in the future for math.
Running the automation, got the error:
08/08/23 12:21:30 pm (2810007)Hourly ValueSOME ERRORS0.17s 
Action details:

Execute a ScriptRunner script action for Automation for Jira

Script function failed on Automation for Jira rule:
Script function failed on Automation for Jira rule: Hourly Value, file: <inline script>, error: java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Double (java.lang.String and java.lang.Double are in module java.base of loader 'bootstrap').
Markus W_ BENES
Contributor
August 8, 2023 edited

@Humberto Gomes is this working?

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem
import com.atlassian.jira.issue.watchers.WatcherManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.util.ImportUtils
import com.atlassian.crowd.embedded.api.User
import com.atlassian.mail.Email
import com.atlassian.mail.server.MailServerManager
import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.issue.IssueInputParametersImpl
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.workflow.JiraWorkflow
import com.atlassian.jira.workflow.WorkflowManager
import com.atlassian.jira.issue.label.Label
import com.atlassian.jira.issue.link.RemoteIssueLinkManager


def customFieldId = "customfield_13900" // Replace this with the actual custom field ID

// Get the current issue
def toChangeIssue = issue.getKey()

// Get the reporter's email
def reporterEmail =  issue.reporter?.emailAddress

// Define the custom field values based on the reporter's email
def customFieldValue = 0.0 // Default value

if (reporterEmail == "Humberto@mail.com") {
customFieldValue = 12.0
} else if (reporterEmail == "Bernardo@mail.com") {
customFieldValue = 16.5
} else if (reporterEmail == "Hugo@mail.com") {
customFieldValue = 12.5
}
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject(toChangeIssue)

def customFieldManager = ComponentAccessor.getCustomFieldManager()
def Object cField

cField = customFieldManager.getCustomFieldObject(customFieldId.toLowerCase());        

def cFieldValue = issue.getCustomFieldValue(cField)
def tgtField = cField
def changeHolder = new DefaultIssueChangeHolder()
       
tgtField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(tgtField), customFieldValue),changeHolder)  
Markus W_ BENES
Contributor
August 8, 2023 edited

@Humberto Gomes Is the script working with strings? I dont believe you have a custom field in integer because of the error message you get. You can transform your value before update into a string:

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.comments.CommentManager
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem
import com.atlassian.jira.issue.watchers.WatcherManager
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.user.util.UserManager
import com.atlassian.jira.util.ImportUtils
import com.atlassian.crowd.embedded.api.User
import com.atlassian.mail.Email
import com.atlassian.mail.server.MailServerManager
import com.atlassian.mail.server.SMTPMailServer
import com.atlassian.jira.issue.IssueInputParametersImpl
import com.atlassian.jira.bc.issue.IssueService
import com.atlassian.jira.workflow.JiraWorkflow
import com.atlassian.jira.workflow.WorkflowManager
import com.atlassian.jira.issue.label.Label
import com.atlassian.jira.issue.link.RemoteIssueLinkManager


def customFieldId = "customfield_13900" // Replace this with the actual custom field ID

// Get the current issue
def toChangeIssue = issue.getKey()

// Get the reporter's email
def reporterEmail =  issue.reporter?.emailAddress

// Define the custom field values based on the reporter's email
def customFieldValue = 0.0 // Default value

if (reporterEmail == "Humberto@mail.com") {
customFieldValue = 12.0
else if (reporterEmail == "Bernardo@mail.com") {
customFieldValue = 16.5
else if (reporterEmail == "Hugo@mail.com") {
customFieldValue = 12.5
}
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject(toChangeIssue)

def customFieldManager = ComponentAccessor.getCustomFieldManager()
def Object cField

cField = customFieldManager.getCustomFieldObject(customFieldId.toLowerCase());        

def cFieldValue = issue.getCustomFieldValue(cField)
def tgtField = cField
def changeHolder = new DefaultIssueChangeHolder()
       
tgtField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(tgtField), customFieldValue.toString()),changeHolder)
Ram Kumar Aravindakshan _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.
August 8, 2023 edited

Hi @Humberto Gomes

If you are using Automation, all you have to do for Issue Created / Issue Update is this:-

import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue

def currentIssue = issue as MutableIssue
def reporter = currentIssue.reporter
def customFieldManager = ComponentAccessor.customFieldManager
def issueManager = ComponentAccessor.issueManager
def sampleNumber = customFieldManager.getCustomFieldObjectsByName('Sample Number').first()

if (reporter.emailAddress == 'user1@mail.com') {
currentIssue.setCustomFieldValue(sampleNumber, Double.parseDouble('1.5'))
} else if (reporter.emailAddress == 'user2@mail.com') {
currentIssue.setCustomFieldValue(sampleNumber, Double.parseDouble('2.5'))
}

issueManager.updateIssue(currentUser, currentIssue, EventDispatchOption.DO_NOT_DISPATCH, false)

Below is a screenshot of the Automation configuration:-

Automation_Config.png

I have tested this code, and it is working in my environment.

Below is a test screenshot for your reference:-

test1.png

I hope this helps to solve your question. :-)

I am looking forward to your feedback. 

Thank you and Kind regards,
Ram

Ram Kumar Aravindakshan _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.
August 8, 2023 edited

@Markus W_ BENES 

A minor suggestion. When you have a solution to suggest, it would be best to add it using Suggest an Answer for the first time instead of the reply so it is easier to identify your solution.

suggestion.png

Like Markus W_ BENES likes this
Humberto Gomes
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 8, 2023

@Markus W_ BENES 

 

No, is not working.

ScreenHunter 1721.png ScreenHunter 1722.png ScreenHunter 1719.png ScreenHunter 1720.png

Like Markus W_ BENES likes this
Markus W_ BENES
Contributor
August 8, 2023

Thank you for this info :)

Ram Kumar Aravindakshan _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.
August 8, 2023 edited

Hi @Humberto Gomes

Have you given a try to the latest solution I have suggested above, i.e.:-

If you are using Automation, all you have to do for Issue Created / Issue Update is this:-

import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue

def currentIssue = issue as MutableIssue
def reporter = currentIssue.reporter
def customFieldManager = ComponentAccessor.customFieldManager
def issueManager = ComponentAccessor.issueManager
def sampleNumber = customFieldManager.getCustomFieldObjectsByName('Sample Number').first()

if (reporter.emailAddress == 'user1@mail.com') {
currentIssue.setCustomFieldValue(sampleNumber, Double.parseDouble('1.5'))
} else if (reporter.emailAddress == 'user2@mail.com') {
currentIssue.setCustomFieldValue(sampleNumber, Double.parseDouble('2.5'))
}

issueManager.updateIssue(currentUser, currentIssue, EventDispatchOption.DO_NOT_DISPATCH, false)

Below is a screenshot of the Automation configuration:-

Automation_Config.png

I have tested this code, and it is working in my environment.

Below is a test screenshot for your reference:-

test1.png

I hope this helps to solve your question. :-)

I am looking forward to your feedback. 

Thank you and Kind regards,
Ram

If yes, may I know the result?

Thank you and Kind regards,

Ram

Markus W_ BENES
Contributor
August 8, 2023 edited

@Humberto Gomes the failure lies definitifely within variable declaration; but i think the code of @Ram Kumar Aravindakshan _Adaptavist_  should be working; its operating with double :)

1 vote
Humberto Gomes
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 8, 2023

Well,
What an incredible journey here. This lengthy process has culminated in success, much like the common saying: works like a charm.

@Ram Kumar Aravindakshan _Adaptavist_  and  @Markus W_ BENES 
I extend my sincere gratitude for your dedication, efforts, and exceptional expertise in assisting me with this matter. Thanks so much.


As I indicated at the outset, this merely constitutes the initial phase of a substantial project in progress... 

 

final script: (used in a automation triggered once the ticket is created)

//////////////////////////////////////////////////////

import com.atlassian.jira.event.type.EventDispatchOption
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.MutableIssue

def currentIssue = issue as MutableIssue
def reporter = currentIssue.reporter
def customFieldManager = ComponentAccessor.customFieldManager
def issueManager = ComponentAccessor.issueManager
def sampleNumber = customFieldManager.getCustomFieldObjectsByName('Hourly Value').first()

if (reporter.emailAddress == 'Humberto@mail.com') {
   currentIssue.setCustomFieldValue(sampleNumber, Double.parseDouble('1.5'))
} else if (reporter.emailAddress == 'Bernardo@mail.com') {
  currentIssue.setCustomFieldValue(sampleNumber, Double.parseDouble('2.5'))
}

issueManager.updateIssue(currentUser, currentIssue, EventDispatchOption.DO_NOT_DISPATCH, false)
////////////////////////////////////////////////////
0 votes
Humberto Gomes
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 8, 2023 edited

Solved

0 votes
Markus W_ BENES
Contributor
August 7, 2023 edited

@Humberto Gomes iam a beginner on my own; but just for the beginning i hope this is of use for you; kudos and a like appreciated if you like it :D

and have a nice day

 

import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import com.atlassian.jira.issue.ModifiedValue
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.Issue

// Key of the Issue that should be changed
def toChangeIssue = "IT-12345" // for actual event -> issue.getKey()

////// Customfields (CF_) //////
def toChangeIssueCustomFields = ["Customfield_12345"] // for no change [""] else [["Customfield_12345", "Last Customfield_23456"]] and so on
def toChangeIssueCustomFieldsValues = [""] // for no change [] else [["Value 1", "Value 2"]] and so on
def toChangeIssueCustomFieldsCheckReporter = true // true or false if set then switch below is working

// search for Issue by Key
IssueManager im = ComponentAccessor.getIssueManager()
MutableIssue issue = im.getIssueObject(toChangeIssue)

// if issue exist then
if(issue){

// run through customfield Array
if(toChangeIssueCustomFields.size() > 0 && toChangeIssueCustomFields[0] != "") {

if(toChangeIssueCustomFieldsCheckReporter == true) {

// get Issue Reporter
def reporter = issue.getReporter()
def reporterName = reporter.getName()

switch(reporterName) {

case "A@mail.com":
toChangeIssueCustomFieldsValues = ["1"]
break;
case "B@mail.com":
toChangeIssueCustomFieldsValues = ["1.2"]
break;
case "C@mail.com":
toChangeIssueCustomFieldsValues = ["2.23"]
break;
default:
toChangeIssueCustomFieldsValues = [""]
break;

}

}

// for each vustomfield in array
toChangeIssueCustomFields.eachWithIndex{ item, index ->

// search field
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def Object cField

// check if custom field is defined by complete name or ID
if (toChangeIssueCustomFields[index].toLowerCase().contains("customfield") == true) {
cField = customFieldManager.getCustomFieldObject(toChangeIssueCustomFields[index].toLowerCase());
} else {
cField = customFieldManager.getCustomFieldObjectByName(toChangeIssueCustomFields[index])
}

def cFieldValue = issue.getCustomFieldValue(cField)

def tgtField = cField
def changeHolder = new DefaultIssueChangeHolder()

// set new value
tgtField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(tgtField), toChangeIssueCustomFieldsValues[index]),changeHolder)

}

}

return true

// if issue doesnt exist
} else {

return false
}

Suggest an answer

Log in or Sign up to answer
DEPLOYMENT TYPE
SERVER
TAGS
atlassian, atlassian government cloud, fedramp, webinar, register for webinar, atlassian cloud webinar, fedramp moderate offering, work faster with cloud

Unlocking the future with Atlassian Government Cloud ☁️

Atlassian Government Cloud has achieved FedRAMP Authorization at the Moderate level! Join our webinar to learn how you can accelerate mission success and move work forward faster in cloud, all while ensuring your critical data is secure.

Register Now
AUG Leaders

Atlassian Community Events