Just a heads up: On March 24, 2025, starting at 4:30pm CDT / 19:30 UTC, the site will be undergoing scheduled maintenance for a few hours. During this time, the site might be unavailable for a short while. Thanks for your patience.

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

Scriptrunner Behavior for a Custom Field Value to require Issue Linking

Brett Beeman August 15, 2024 edited

I am trying to setup a behavior where if a user selects the value "IR Linked" for custom field "IR Evaluation" ("customfield_17007"), then an issue must be linked on that same Resolve transition screen. I.E Issue Links field is required. If any other value is selected, then an issue link is not required.

Also trying to force only two issue link types to be available: "Creates" or "Relates to"

I've been scouring the internet for answers, but the scripts I am putting together are duds. Help Needed! Thanks in advance. 

 

 

import com.atlassian.jira.issue.fields.CustomField
import com.atlassian.jira.issue.CustomFieldManager
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.link.IssueLink

def issuelinktypesField = getFieldByName('issuelinks-linktype')
def issuelinksField = getFieldByName('issuelinks-issues')
def IREvaluationField = getFieldByName("IR Evaluation")

def selectedOption = IREvaluationField.getCustomFieldvalue("IR Linked") as String
def IRLinkedSelected = selectedOption == "IR Linked"

issuelinktypesField.setHidden(! IRLinkedSelected)
issuelinksField.setHidden(! IRLinkedSelected)
issuelinktypesField.setRequired(IRLinkedSelected)
issuelinksField.setRequired(IRLinkedSelected)

1 answer

1 accepted

2 votes
Answer accepted
Radek Dostál
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 16, 2024 edited

Well there are a lot of incorrect getters and comparators in your example but you structured it in a good way so I decided to give it a shot. Took a little bit I'll give you that and I had to sort a few glitches to get it going, but alas I think this works..

 

Transition screen

My test includes just IR Evaluation and Linked Issues, no more no less. Other fields should not matter in this if you have more.

 

Behaviour setup - General

Mapped to project/issuetypes as needed

Guide workflow: the one you use for that issue type

Initializer: EMPTY

 

Field 1 - IR Evaluation

Conditions: When (Workflow Action: XX); where you select the transition you want this to work on

 

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.link.IssueLinkTypeManager
import com.onresolve.jira.groovy.user.FormField

FormField irEvaluationField = getFieldById(getFieldChanged())
FormField issueLinkTypesField = getFieldById('issuelinks-linktype')
FormField issuesField = getFieldById("issuelinks-issues")

if ("IR Linked".equals(irEvaluationField.getValue())) {
    String[] allowedOutwardTypes = new String[]{"Creates", "Relates to"}
    Map<String, String> allowedIssueLinkTypesMap = (Map<String, String>) ComponentAccessor.getComponent(IssueLinkTypeManager).getIssueLinkTypes(false).stream()
            .filter(linkType -> allowedOutwardTypes.contains(linkType.getOutward()))
            .reduce(new HashMap<String, String>(), (map, element) -> {
                map.put(element.getOutward(), element.getOutward())
                return map
            },
            (map1, map2) -> {
                map1.putAll(map2)
                return map1
            })

    issueLinkTypesField.setFieldOptions(allowedIssueLinkTypesMap)
    issueLinkTypesField.setHidden(false)
    issueLinkTypesField.setRequired(true)

    if (((List) issuesField.getValue()).isEmpty())
        issuesField.setError("You must link at least 1 issue.")
    else
        issuesField.clearError()
}
else {
    issuesField.clearError()
    issueLinkTypesField.setRequired(false)
    issueLinkTypesField.setHidden(true)
}

 

Field 2 - Linked Issues

Conditions: When (Workflow Action: XX); where you select the transition you want this to work on

 

import com.onresolve.jira.groovy.user.FormField

FormField issuesField = getFieldById("issuelinks-issues")
FormField
irEvaluationField = getFieldByName("IR Evaluation")

if
("IR Linked".equals(irEvaluationField.getValue()) && ((List) issuesField.getValue()).isEmpty()) {
    issuesField.setError("You must link at least 1 issue.")
}
else {
    issuesField.clearError()

}

 

Why are there 2 fields? Normally, we could make this work with just one (the IR Evaluation). However, Linked Issues is kind of special and setting it as required doesn't work. While we can instead use 'setError()/clearError()' - which will prevent the transition - we still need to check that an issue has been added, but we cannot do this from the parent field, as at the time the IR Evaluation is set, we expect there not to be any issue at all, so we just can't go from here.

That is why we add the second field 'Linked Issues'. Luckily, when we add a linked issue, this triggers the behaviour. If it did not, I think we couldn't use behaviours at all and would have to use a workflow validator instead.

When a linked issue is added, the behaviour is triggered, and it simply checks if we still have the 'IR Evaluation' set and whether the changed issue count is greater than 0. If so, we're happy and can clearError(), if we haven't done anything or have removed any linked issue, we default back to setError() to prevent the transition.

 

One point I would mention is that I noticed you were hiding issue links when IR Evaluation was not IR Linked. So, in this script, as soon as you select IR Linked, it will permanently restrict the available issue link types. If you ever need issue links to work without IR Linked and contain all available link types (rather than just the 2), then it would need to be unbricked back, but I skipped it seeing as it wasn't needed for now.

 

Edit:

minor manual code cleanup, hopefully without typos, code block is pain in the neck and usually doesn't work..

fixed the 'TR Linked' 'IR Linked' mixup which is why this probably didn't work right out of the box

better explanation for the need of 2 fields

 

Brett Beeman August 16, 2024 edited

I think this is definitely on the right track, as I see the Linked Issues & Issue fields now have a red asterisk, when IR Evaluation = IR Linked. However, the Linked Issues field does not have any selections to chose from (Created or Relates to).

Any ideas?

Brett Beeman August 16, 2024

I have validators setup through Jira natively on this same Resolve transition. Do all validators need to be run through Scriptrunner for this to execute properly?

Brett Beeman August 16, 2024

@Radek Dostál - You're a legend for this. I had to make one slight modification, but otherwise what you provided works exactly how I had envisioned it. Thanks for your help on this.

Suggest an answer

Log in or Sign up to answer
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, our FedRAMP Moderate offering, is coming soon! 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

Upcoming Jira Events