Forums

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

How do I bulk edit saved filters in ScriptRunner?

Diana
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 Champions.
September 21, 2022

We have a custom field called "Team" and it has single select values [Team A, Team B, Team C etc].

Team A decides to change their name to Team A-1. It's not a problem to edit the custom field values in the Jira admin settings, and all the issues gets updated. But all saved filters that still uses jql "Team = 'Team A'" does not get changed when the custom field value is edited.

I'm trying to get a script to run on Console that will first find all saved filters that contains "Team = Team A". Then, print the results to show the filter owner, query string, and filter name.

Then, the second run, get all those filters and update the string to be "Team = Team A-1".

But the code I run won't make the replaceAll changes. I'm using custom field ID in case I want to reuse this script for another custom field.

 

import com.atlassian.jira.bc.JiraServiceContextImpl
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.bc.filter.SearchRequestService
import com.atlassian.jira.issue.search.SearchRequest
import com.atlassian.jira.bc.user.search.UserSearchParams
import com.atlassian.jira.bc.user.search.UserSearchService
import java.lang.StringBuffer
import java.lang.StringBuilder
import com.atlassian.jira.jql.parser.JqlQueryParser


SearchRequestService searchRequestService = ComponentAccessor.getComponent(SearchRequestService.class)
UserSearchService userSearchService = ComponentAccessor.getComponent(UserSearchService)
def sb = new StringBuffer()
def jqlQueryParser = ComponentAccessor.getComponent(JqlQueryParser)

UserSearchParams userSearchParams = new UserSearchParams.Builder()
.allowEmptyQuery(true)
.includeInactive(false)
.ignorePermissionCheck(true)
.maxResults(5000)
.build()


//iterate over each user's filters
userSearchService.findUsers("", userSearchParams).each{ApplicationUser filter_owner ->
try {
searchRequestService.getOwnedFilters(filter_owner).each{SearchRequest filter->
String jql = filter.getQuery().toString()
def customField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(10800)//using ID if need to reuse this script for another field
def oldJQL = customField = A as String
def newJQL = customField = A-1 as String
def context = new JiraServiceContextImpl(filter_owner)
if (jql.contains(oldJQL) {
//jql.replaceAll(oldJQL, newJQL) //commented out because still not working
sb.append("Found: ${filter_owner.displayName}, ${filter.name}, ${filter.getPermissions().isPrivate() ? 'Private' : 'Shared'}, ${jql}\n")
}
}
} catch (Exception e) {
//if filter is private
sb.append("Unable to get filters for ${filter_owner.displayName} due to ${e}")
}
}

//output results
return sb.toString()

Any suggestions?

Side question: is something like this possible using REST API? Any guidance on that?

3 answers

Suggest an answer

Log in or Sign up to answer
0 votes
Scott Boisvert
Community Champion
December 3, 2020

I know this is two years old, but is there a solution to this. My scripted field works fine on the view screen, but adding the javascript recommended by Adapatvist/ScriptRunner Scripted Fields just displays the script on the screen under the field I place it in.

Joanna Choules
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 Champions.
January 6, 2021

Hi Scott,

Can you describe exactly where you're adding the JS?

Scott Boisvert
Community Champion
January 6, 2021

@Joanna Choules The script goes in the description of another field on the screen. The issue I was having though is that you have to have Allow HTML In Custom Field Descriptions enabled, it was disabled in our environment.

Joanna Choules
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 Champions.
January 6, 2021

Hi Scott,

Thanks for letting me know. Did enabling that option resolve the issue for you?

Scott Boisvert
Community Champion
January 6, 2021

@Joanna Choules Yep it did.

0 votes
Ashraful Hasan [Adaptavist]
Contributor
February 2, 2018

Hi,

Please add the javascript code and also please confirm the JIRA and SR version? From the ticket I can see the version of JIRA is 7.6.1 and SR 5.2.2.

DerekWilliamsGenscape
February 2, 2018

yes that is correct. Here is the JS

 

<script type="text/javascript">
(function ($) {

    // ---------------------------------- MANDATORY CONFIG ----------------------------------
    var fieldName = "Octopus Release" // display name - does not have to match the name of the field
    var fieldId = "customfield_13154" // field Id
    // ---------------------------------- END MANDATORY CONFIG ------------------------------

    function addCalculatedField(e, context) {
        var $context = $(context);

        // if you want you can limit this to certain actions by checking to see if this value is in a list of action IDs
        if (!$("input[name='action']").val()) {
            return;
        }

        // multiple handlers can be added if you do an action, then cancel repeatedly
        if ($context.find("#scriptedfield_" + fieldId).length > 0) {
            return;
        }

        var issueKey = $("meta[name='ajs-issue-key']").attr("content");
        if (!issueKey) {
            issueKey = $("#key-val").attr("rel"); // transition screens in full page mode
        }

        var paddingTop = AJS.$("meta[name='ajs-build-number']").attr("content") < 6000 ? "1" : "5";

        var fieldGroupHtml = '<div class="field-group">' +
            '<label for="' + fieldId + '">' + fieldName + '</label>' +
            '<div style="padding-top: ' + paddingTop + 'px" id="scriptedfield_' + fieldId + '"> ' +
            '<span class="aui-icon aui-icon-wait">Loading, please wait</span></div>' +
            '</div> ';

        // Modify this select if you want to change the positioning of the displayed field
        $context.find("div.field-group:first").before(fieldGroupHtml);

        $.ajax({
            type: "GET",
            "contentType": "application/json",
            url: AJS.params.baseURL + "/rest/api/2/issue/" + issueKey + "?expand=renderedFields&fields=" + fieldId,
            success: function (data) {
                if ("fields" in data && fieldId in data.fields) {
                    var fieldValue = data.fields[fieldId];
                    $context.find("#scriptedfield_" + fieldId).empty().append(fieldValue);
                }
                else {
                    $context.find("#scriptedfield_" + fieldId).empty().append("ERROR - bad field ID");
                }
            },
            error: function () {
                $context.find("#scriptedfield_" + fieldId).empty().append("ERROR");
            }
        });
    }

    JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function (e, context) {
        addCalculatedField(e, context);
    });

})(AJS.$);
</script>
DerekWilliamsGenscape
February 2, 2018

So my comment disappeared....Those versions are correct. Here is the JS

 

<script type="text/javascript">
(function ($) {

    // ---------------------------------- MANDATORY CONFIG ----------------------------------
    var fieldName = "Octopus Release" // display name - does not have to match the name of the field
    var fieldId = "customfield_13154" // field Id
    // ---------------------------------- END MANDATORY CONFIG ------------------------------

    function addCalculatedField(e, context) {
        var $context = $(context);

        // if you want you can limit this to certain actions by checking to see if this value is in a list of action IDs
        if (!$("input[name='action']").val()) {
            return;
        }

        // multiple handlers can be added if you do an action, then cancel repeatedly
        if ($context.find("#scriptedfield_" + fieldId).length > 0) {
            return;
        }

        var issueKey = $("meta[name='ajs-issue-key']").attr("content");
        if (!issueKey) {
            issueKey = $("#key-val").attr("rel"); // transition screens in full page mode
        }

        var paddingTop = AJS.$("meta[name='ajs-build-number']").attr("content") < 6000 ? "1" : "5";

        var fieldGroupHtml = '<div class="field-group">' +
            '<label for="' + fieldId + '">' + fieldName + '</label>' +
            '<div style="padding-top: ' + paddingTop + 'px" id="scriptedfield_' + fieldId + '"> ' +
            '<span class="aui-icon aui-icon-wait">Loading, please wait</span></div>' +
            '</div> ';

        // Modify this select if you want to change the positioning of the displayed field
        $context.find("div.field-group:first").before(fieldGroupHtml);

        $.ajax({
            type: "GET",
            "contentType": "application/json",
            url: AJS.params.baseURL + "/rest/api/2/issue/" + issueKey + "?expand=renderedFields&fields=" + fieldId,
            success: function (data) {
                if ("fields" in data && fieldId in data.fields) {
                    var fieldValue = data.fields[fieldId];
                    $context.find("#scriptedfield_" + fieldId).empty().append(fieldValue);
                }
                else {
                    $context.find("#scriptedfield_" + fieldId).empty().append("ERROR - bad field ID");
                }
            },
            error: function () {
                $context.find("#scriptedfield_" + fieldId).empty().append("ERROR");
            }
        });
    }

    JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function (e, context) {
        addCalculatedField(e, context);
    });

})(AJS.$);
</script>
Joanna Choules
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 Champions.
February 15, 2018

Hi Derek,

What previewing functionality did you use to check that the code was working? I believe you should only need to add the code to the description of one of the fields that appears on the appropriate screen.

DerekWilliamsGenscape
February 27, 2018

I would just preview by returning a select option. However, if I add the javascript to the description field of the context, nothing shows up. Note there is not a description field of the scripted field. If one exists it is not called description.

DerekWilliamsGenscape
March 28, 2018

Any thoughts here? I am frustrated with this platform.

Sandor Mathe
November 3, 2018

Hello,

Is there a resolution for this problem? I encountered the same issue...

0 votes
DerekWilliamsGenscape
January 22, 2018

For more detail, it does not appear that I can even get the blank custom field to show on transition screens. I have pasted the Javascript code in every single 'description' field (citation the article) that I can find as it related to field configurations.

Natalie Al-Delemi
January 16, 2024

I know this is a few years old question, but you will need:

1- Make sure HTML is enabled on custom fields in system general configuration

2- paste the script in description of the other field that controls the value of the scripted field. 

3- Make sure the field ID is correct in the script.

you will then see that it works.. It worked for me

TAGS
AUG Leaders

Atlassian Community Events