Forums

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

Update the custom field value based on jql results while creating the ticket

Lakshmi CH
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 10, 2020

Hi Team,

I tried with something, but I am sure it is not perfect. Could you please help on correct script.

If we create a filter for our JIRA workflow like: “Hub ID” in (xxx, abc, def, 123, etc)  is there any way to have tickets run that filter upon creation and then dynamically update a field to either be checked as “yes” or “no”.

 

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.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()

// JQL Query
def query = jqlQueryParser.parseQuery("project = MD AND ("Hub ID" ~ 504 OR "Hub ID" ~ TST)")


// the name of the custom field to update
final String customFieldName = 'Risk Hub Id'

// the new value of the field
final String newValue = 'Yes'

def customFieldManager = ComponentAccessor.customFieldManager
def issue = event.issue

def customField = customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
assert customField : "Could not find custom field with name $customFieldName"

if (query.isValid()) {

customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValue), new DefaultIssueChangeHolder())

}

1 answer

0 votes
Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 11, 2020

hi @Lakshmi CH your script is not correct. I will try to give you needed snippets :) You're not using results of query in your snippet but only "isValid" which is not enought I guess. In my snippet I'm evaluating issues count and if the count is > 0, value in "customField" is filled in with newValue.

def jqlToSearch = "project = MD AND ("Hub ID" ~ 504 OR "Hub ID" ~ TST)"
def parseResult = searchService.parseQuery(user, jqlToSearch)
log.error("jql: " + jqlToSearch)
if (parseResult.isValid()) {
def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
if(searchResult.issues.size()>0) {
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValue), new DefaultIssueChangeHolder())
}
}

give it a try and let me know what exactly is not working and we will fix it :)

Lakshmi CH
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 13, 2020

Thank you for your response @Martin Bayer _MoroSystems_ s_r_o__ , I tried with below code and did not see any errors, but its the value of Risk Hub Id "Yes" in not displaying in the ticket, I have added this script to custom script post function and put it in first post function of the workflow.

 

 

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.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()


// the name of the custom field to update
final String customFieldName = 'Risk Hub Id'

// the new value of the field
final String newValue = 'Yes'

def customFieldManager = ComponentAccessor.customFieldManager
def issue = event.issue

def customField = customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
assert customField : "Could not find custom field with name $customFieldName"

def jqlToSearch = "project = MD AND ("Hub ID" ~ 504 OR "Hub ID" ~ TST)"
def parseResult = searchService.parseQuery(user, jqlToSearch)
log.error("jql: " + jqlToSearch)
if (parseResult.isValid()) {
def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
if(searchResult.issues.size()>0) {
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValue), new DefaultIssueChangeHolder())
}
}

Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 13, 2020

If you can't view the field, are you sure the field is on VIEW screen? Can you edit the field manually?

Lakshmi CH
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 13, 2020

Yes @Martin Bayer _MoroSystems_ s_r_o__ , I have added manually, and able to see it. These are the errors. I put it on first post function on create.

 

Time (on server): Mon Jul 13 2020 18:49:38 GMT+0530 (India Standard Time)

The following log information was produced by this execution. Use statements like:log.info("...") to record logging information.

2020-07-13 13:19:38,208 ERROR [workflow.AbstractScriptWorkflowFunction]: *************************************************************************************
2020-07-13 13:19:38,209 ERROR [workflow.AbstractScriptWorkflowFunction]: Script function failed on issue: null, actionId: 1, file: null
groovy.lang.MissingPropertyException: No such property: event for class: Script451
	at Script451.run(Script451.groovy:20)

{
    "canned-script": "com.onresolve.scriptrunner.canned.jira.workflow.postfunctions.CustomScriptFunction (java.lang.String)",
    "class.name": "com.onresolve.jira.groovy.GroovyFunctionPlugin (java.lang.String)",
    "full.module.key": "com.onresolve.jira.groovy.groovyrunnerrungroovy-function (java.lang.String)",
    "issue": "testing hub id (com.atlassian.jira.issue.IssueImpl)",
    "passesCondition": "true (java.lang.Boolean)",
    "transientVars": {
        "entry": "com.opensymphony.workflow.spi.SimpleWorkflowEntry@6529f48",
        "issue": "testing hub id (com.atlassian.jira.issue.IssueImpl)",
        "configuration": "com.opensymphony.workflow.config.DefaultConfiguration@2a24585f",
        "context": "com.opensymphony.workflow.basic.BasicWorkflowContext@7ee33517",
        "createdStep": "SimpleStep@1[owner=, actionId=0, status=open] (com.opensymphony.workflow.spi.SimpleStep)",
        "originalissueobject": "null (org.codehaus.groovy.runtime.NullObject)",
        "actionId": "1 (java.lang.Integer)",
        "issueProperties": "{} (com.google.common.collect.RegularImmutableMap)",
        "currentSteps": "[SimpleStep@1[owner=, actionId=0, status=open]] (java.util.ArrayList)",
        "pkey": "MD (java.lang.String)",
        "store": "com.opensymphony.workflow.spi.ofbiz.OfbizWorkflowStore@421d9ae2",
        "descriptor": "com.atlassian.jira.workflow.ImmutableWorkflowDescriptor@55bf5530"
    },
    "log": "org.apache.log4j.Logger@1c043db0",
    "£beanContext": "com.onresolve.scriptrunner.beans.BeanFactoryBackedBeanContext@677b1ae5"
}

 

Lakshmi CH
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 13, 2020

Hi @Martin Bayer _MoroSystems_ s_r_o__ ,

 I am seeing the error when copied same code in listener.

code.PNG

Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 13, 2020

@Lakshmi CH and do you want to run the code as postfunction or listener? For postfunction it is enough to remove "def issue = event.issue" also jqlToSearch is not valid, it should be

def jqlToSearch = "project = MD AND ('Hub ID ' ~ '584' OR 'Hub ID' ~ 'TST)"
Lakshmi CH
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 14, 2020

@Martin Bayer _MoroSystems_ s_r_o__, anything is ok,, right now I am trying with post function. Seems its not working.

 

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.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()


// the name of the custom field to update
final String customFieldName = 'Risk Hub Id'

// the new value of the field
final String newValue = 'Yes'

def customFieldManager = ComponentAccessor.customFieldManager

def customField = customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
assert customField : "Could not find custom field with name $customFieldName"

def jqlToSearch = "project = MD AND ('Hub ID ' ~ '584' OR 'Hub ID' ~ 'TST)"
def parseResult = searchService.parseQuery(user, jqlToSearch)
log.error("jql: " + jqlToSearch)
if (parseResult.isValid()) {
    def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
    if(searchResult.issues.size()>0) {
        customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValue), new DefaultIssueChangeHolder())
    }
}

Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 14, 2020

Can you add some "log.error" logging to IF conditions just to know that conditions or results of JQL searching is ok?

Lakshmi CH
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 14, 2020

Is this right ?

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.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import org.apache.log4j.Category

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()


// the name of the custom field to update
final String customFieldName = 'Risk Hub Id'

// the new value of the field
final String newValue = 'Yes'

def customFieldManager = ComponentAccessor.customFieldManager

def customField = customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
assert customField : "Could not find custom field with name $customFieldName"

def jqlToSearch = "project = MD AND ('Hub ID ' ~ '584' OR 'Hub ID' ~ 'TST)"
def parseResult = searchService.parseQuery(user, jqlToSearch)
log.error("jql: " + jqlToSearch)
if (parseResult.isValid()) {
    def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
    if(searchResult.issues.size()>0) {
          customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValue), new DefaultIssueChangeHolder())
          log.error ("JQL $jql:")

       
    }
}

Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 14, 2020

Yeah it looks correct. Just give it a try and post the log records here

Lakshmi CH
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 14, 2020

Hi @Martin Bayer _MoroSystems_ s_r_o__ ,

Time (on server): Tue Jul 14 2020 18:33:16 GMT+0530 (India Standard Time)

The following log information was produced by this execution. Use statements like:log.info("...") to record logging information.

2020-07-14 13:03:16,911 ERROR [workflow.AbstractScriptWorkflowFunction]: *************************************************************************************
2020-07-14 13:03:16,912 ERROR [workflow.AbstractScriptWorkflowFunction]: Script function failed on issue: null, actionId: 1, file: null
groovy.lang.MissingPropertyException: No such property: Hub for class: Script558
 at Script558.run(Script558.groovy:25)












 

{
    "canned-script": "com.onresolve.scriptrunner.canned.jira.workflow.postfunctions.CustomScriptFunction (java.lang.String)",
    "class.name": "com.onresolve.jira.groovy.GroovyFunctionPlugin (java.lang.String)",
    "full.module.key": "com.onresolve.jira.groovy.groovyrunnerrungroovy-function (java.lang.String)",
    "issue": "Testing (com.atlassian.jira.issue.IssueImpl)",
    "passesCondition": "true (java.lang.Boolean)",
    "transientVars": {
        "entry": "com.opensymphony.workflow.spi.SimpleWorkflowEntry@6b16a9f6",
        "issue": "Testing (com.atlassian.jira.issue.IssueImpl)",
        "configuration": "com.opensymphony.workflow.config.DefaultConfiguration@2a24585f",
        "context": "com.opensymphony.workflow.basic.BasicWorkflowContext@d2253f1",
        "createdStep": "SimpleStep@1[owner=, actionId=0, status=open] (com.opensymphony.workflow.spi.SimpleStep)",
        "originalissueobject": "null (org.codehaus.groovy.runtime.NullObject)",
        "actionId": "1 (java.lang.Integer)",
        "issueProperties": "{} (com.google.common.collect.RegularImmutableMap)",
        "currentSteps": "[SimpleStep@1[owner=, actionId=0, status=open]] (java.util.ArrayList)",
        "pkey": "MD (java.lang.String)",
        "store": "com.opensymphony.workflow.spi.ofbiz.OfbizWorkflowStore@421d9ae2",
        "descriptor": "com.atlassian.jira.workflow.ImmutableWorkflowDescriptor@4d728588"
    },
    "log": "org.apache.log4j.Logger@1c043db0",
    "£beanContext": "com.onresolve.scriptrunner.beans.BeanFactoryBackedBeanContext@677b1ae5"
}
Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 15, 2020

@Lakshmi CH sorry for later response, I tested it on my environemnt (Jira 8.8.1) and it's working

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.bc.issue.search.SearchService
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.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import org.apache.log4j.Category
import com.atlassian.jira.issue.customfields.manager.OptionsManager

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchService = ComponentAccessor.getComponent(SearchService.class)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def optionsManager = ComponentAccessor.getComponent(OptionsManager)

// the name of the custom field to update
final String customFieldName = 'Risk Hub Id'
def customField = customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
assert customField : "Could not find custom field with name $customFieldName"

// the new value of the field
final String newValue = 'Yes'
def fieldConfig = customField.getRelevantConfig(issue)
def newValueOption = optionsManager.getOptions(fieldConfig).getOptionForValue("Yes", null)

def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

def jqlToSearch = "project = MD AND ('Hub ID' ~ '584' OR 'Hub ID' ~ 'TST')"
def parseResult = searchService.parseQuery(user, jqlToSearch)
log.error("jql: " + jqlToSearch)
if (parseResult.isValid()) {
log.error("parse result valid")
def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
if(searchResult.getResults().size()>0) {
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValueOption), new DefaultIssueChangeHolder())
log.error ("JQL:" + jqlToSearch)


}
}else{
log.error(parseResult.errors)
log.error("parse result invalid")
}
Lakshmi CH
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 16, 2020

Thank you so much for helping on this @Martin Bayer _MoroSystems_ s_r_o__ .  I see below errors, but script was passed, but the Risk Hub Id is not updated with "Yes" in the ticket. The field was on all screens.

 

FYI, I put it on first post function on create transition, and the Risk Hub id is single line text field.

script.PNG

Time (on server): Thu Jul 16 2020 12:42:41 GMT+0530 (India Standard Time)

The following log information was produced by this execution. Use statements like:log.info("...") to record logging information.

2020-07-16 07:12:41,843 ERROR [runner.ScriptBindingsManager]: jql: project = MD AND ('Hub ID' ~ '584' OR 'Hub ID' ~ 'TST')
2020-07-16 07:12:41,849 ERROR [runner.ScriptBindingsManager]: parse result valid
2020-07-16 07:12:41,855 WARN [permission.DefaultPermissionSchemeManager]: No permission scheme is associated with project 'CS - Archived'
2020-07-16 07:12:41,880 ERROR [runner.ScriptBindingsManager]: JQL:project = MD AND ('Hub ID' ~ '584' OR 'Hub ID' ~ 'TST')

  

Lakshmi CH
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 17, 2020

@Martin Bayer _MoroSystems_ s_r_o__, Any idea, why the field is not showing Yes Value.?

Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 17, 2020

Try to add your postfunction as the Last one and then add postfunction "Store issue", so the last but one postfunction is the one with your script and last one is "Store issue"

Martin Bayer _MoroSystems_ s_r_o__
Community Champion
July 20, 2020

I'm also checking the code and it won't log anything if result set is empty, so try to adjust it:

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.bc.issue.search.SearchService
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.issue.ModifiedValue
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder
import org.apache.log4j.Category
import com.atlassian.jira.issue.customfields.manager.OptionsManager

def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)
def searchService = ComponentAccessor.getComponent(SearchService.class)
def searchProvider = ComponentAccessor.getComponent(SearchProvider)
def issueManager = ComponentAccessor.getIssueManager()
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def optionsManager = ComponentAccessor.getComponent(OptionsManager)

// the name of the custom field to update
final String customFieldName = 'Risk Hub Id'
def customField = customFieldManager.getCustomFieldObjects(issue).findByName(customFieldName)
assert customField : "Could not find custom field with name $customFieldName"

// the new value of the field
final String newValue = 'Yes'
def fieldConfig = customField.getRelevantConfig(issue)
def newValueOption = optionsManager.getOptions(fieldConfig).getOptionForValue("Yes", null)

def user = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

def jqlToSearch = "project = MD AND ('Hub ID' ~ '584' OR 'Hub ID' ~ 'TST')"
def parseResult = searchService.parseQuery(user, jqlToSearch)
log.error("jql: " + jqlToSearch)
if (parseResult.isValid()) {
log.error("parse result valid")
def searchResult = searchService.search(user, parseResult.getQuery(), PagerFilter.getUnlimitedFilter())
if(searchResult.getResults().size()>0) {
customField.updateValue(null, issue, new ModifiedValue(issue.getCustomFieldValue(customField), newValueOption), new DefaultIssueChangeHolder())
log.error ("JQL:" + jqlToSearch)


} else {
log.error("No result found for given JQL")
}
}else{
log.error(parseResult.errors)
log.error("parse result invalid")
}
Lakshmi CH
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 20, 2020

Hi @Martin Bayer _MoroSystems_ s_r_o__ ,

 same error .

Time (on server): Mon Jul 20 2020 18:54:16 GMT+0530 (India Standard Time)

The following log information was produced by this execution. Use statements like:log.info("...") to record logging information.

2020-07-20 13:24:16,134 ERROR [runner.ScriptBindingsManager]: jql: project = MD AND ('Hub ID' ~ '584' OR 'Hub ID' ~ 'TST')
2020-07-20 13:24:16,140 ERROR [runner.ScriptBindingsManager]: parse result valid
2020-07-20 13:24:16,142 WARN [permission.DefaultPermissionSchemeManager]: No permission scheme is associated with project 'CS - Archived'
2020-07-20 13:24:16,161 ERROR [runner.ScriptBindingsManager]: JQL:project = MD AND ('Hub ID' ~ '584' OR 'Hub ID' ~ 'TST')

Cancel

Lakshmi CH
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 21, 2020

Hi @Martin Bayer _MoroSystems_ s_r_o__ , I have put it as first post function of the create transition of the workflow.

Suggest an answer

Log in or Sign up to answer