Help with displaying scripted fields on transition screen

Hello,

I am following Jamie's Javascript solution listed here (https://scriptrunner.adaptavist.com/latest/jira/scripted-fields.html#_displaying_script_fields_in_transition_screens) to display a warning message on a transition screen. I have the javascript added to the "Assignee" field thats added to a screen which is used as a transition screen on multiple transitions and this javascript is calling the "same" scripted field. I would like to display different messages using the scripted field depending on the transition ID. I would like to avoid adding the condition in javascript which would force me to have one scripted field per custom message.

Is there a way to get the current transition ID/Name on the Scripted field to do a condition? It doesnt seem like I can use "transientVars" on the scripted field. If I get the destination status information, that would work too.

 

Thanks in advance

Venkat.

3 answers

This widget could not be displayed.

Hi Venkat,

I don’t think that the scripted field is going to do what you need. I have been playing with it and there doesn’t appear to be a way to link the issue to the transition or action ID. You are right about `transientVars` not being available in this instance.

You mentioned that you wanted to have different warning messages depending on the transition ID (“I would like to display different messages using the scripted field depending on the transition ID”).

You could achieve the same thing using a custom REST endpoint instead of a script field. I propose using the custom REST endpoint to map your transition ID to your warning message, and then use the Javascript to render that response back to the user. The below examples are a working solution for this approach.

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript

import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

@BaseScript CustomEndpointDelegate delegate

warningMessage(
        httpMethod: "GET"
) { MultivaluedMap queryParams, String body ->
    /* In here get the transition ID out and use it to map to a warning message */
    def transIds = queryParams.get("transitionId")
    String transId = transIds.size() > 0 ? transIds[0] : -1
    def warningMsg = warningMsgSwitch(transId.toInteger())

    return Response.ok(new JsonBuilder([msg: warningMsg]).toString()).build()
}

/**
 * A switch that produces a warning message based on the given transition ID.
 * @param val The transition ID to check.
 * @return The warning message.
 */
def warningMsgSwitch(val) {
    def result
    switch (val) {
        case 11:
            result = 'Be careful when changing status back to TODO'
            break
        case 21:
            result = 'Have you done your pre-development checks?'
            break
        case 31:
            result = 'Has the testing been carried out?'
            break
        default:
            result = 'Unrecognised Transition'
            break
    }
    result
}
<script type="text/javascript">
    (function ($) {
        function addCalculatedField(e, context) {
            var $context = $(context);


            /* Get the transition ID */
            var tranId = $("input[name='action']").attr("value");


            $.ajax({
                type: "GET",
                "contentType": "application/json",
                url: AJS.params.baseURL + "/rest/scriptrunner/latest/custom/warningMessage?transitionId=" + tranId,
                success: function (data) {
                    if ("msg" in data) {
                        var warningMsg = data.msg;
                        var newFieldGroupHtml = '<div id="warning-msg" class="aui-message warning draft-workflow-message">' + warningMsg + '</div>';
                        // Here we check to see if the error already exists (we don't want to repeat the insert)
                        if ($("div[id='warning-msg']").length == 0) {
                            // Modify this select if you want to change the positioning of the displayed field
                            $context.find("div.field-group:first").before(newFieldGroupHtml);
                        }
                    }
                },
                error: function () {
                    console.log("Unable to retrieve warning message");
                }
            });


        }


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


    })(AJS.$);
</script>

The basic steps to implement this are ….

  1. Create a REST endpoint using the above source. NOTE: You need to update the switch with your action ID for YOUR transitions.
  2. Add the Javascript source above to your Assignee (or other preferred standard issue field) description field (same as before).
  3. Test 
This widget could not be displayed.

Hi Adam,

First of all thanks a lot for spending time to send me the scripts! Also I apologize for not getting back to you right away. I got pulled into other stuff and finally got a chance to look at your response this morning.

 

Your script works perfectly as-is. I was trying to customize it to include another condition that is based on the Issue history (specifically "Status" field).

<Javascript Below>

Below is my version of REST Endpoint, just incorporating additional condition to display a custom warning message. The same methods that worked fine in the "Scripted Field" wouldnt work in the EndPoint. 

If I have an Issue make these transitions (ID 41 or 91), it would just display the warning messages basically "ignoring" the status history condition. 

I am also attaching screenshots.

<EndPoint Below>


JAVASCRIPT

----------------

Only change I made in the JavaScript is to pass the Issue Key to the EndPoint.

<script type="text/javascript">
(function ($) {
function addCalculatedField(e, context) {
var $context = $(context);


/* Get the transition ID */
var tranId = $("input[name='action']").attr("value");
var issKey = JIRA.Issue.getIssueId();

$.ajax({
type: "GET",
"contentType": "application/json",
url: AJS.params.baseURL + "/rest/scriptrunner/latest/custom/warningMessage?transitionId=" + tranId + "&issueKey=" + issKey,
success: function (data) {
if ("msg" in data) {
var warningMsg = data.msg;
var newFieldGroupHtml = '<div id="warning-msg" class="aui-message warning draft-workflow-message">' + warningMsg + '</div>';
// Here we check to see if the error already exists (we don't want to repeat the insert)
if ($("div[id='warning-msg']").length == 0) {
// Modify this select if you want to change the positioning of the displayed field
$context.find("div.field-group:first").before(newFieldGroupHtml);
}
}
},
error: function () {
console.log("Unable to retrieve warning message");
}
});


}


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


})(AJS.$);
</script>


REST EndPoint

---------------------

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.json.JsonBuilder
import groovy.transform.BaseScript

import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.Issue
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.changehistory.ChangeHistoryManager
import com.atlassian.jira.issue.history.ChangeItemBean
import com.atlassian.jira.issue.CustomFieldManager

@BaseScript CustomEndpointDelegate delegate

warningMessage(
httpMethod: "GET"
) { MultivaluedMap queryParams, String body ->
/* In here get the transition ID out and use it to map to a warning message */
def transIds = queryParams.get("transitionId")
def issKey = queryParams.get("issueKey")
String transId = transIds.size() > 0 ? transIds[0] : -1


def issueManager = ComponentAccessor.getIssueManager()
def issue = issueManager.getIssueObject(issKey)
def changeHistoryManager = ComponentAccessor.getChangeHistoryManager()
def changehistoryItems = changeHistoryManager.getChangeItemsForField(issue, "Status")

if (issue != null){
def historyresult = []
changehistoryItems.each{ChangeItemBean item ->
historyresult << item.getToString()
}

def warningMsg = warningMsgSwitch(transId.toInteger(),issKey,historyresult)
return Response.ok(new JsonBuilder([msg: warningMsg]).toString()).build()
}

}

/**
* A switch that produces a warning message based on the given transition ID.
* @param val The transition ID to check.
* @return The warning message.
*/
def warningMsgSwitch(val,ikey,hisResult) {
def result

if ((val == 41) && (!hisResult.contains("Ready to verify"))) {
result = 'Warning!!You are skipping Test Deployment!!'
result
}
else if ((val == 91) && (!hisResult.contains("Ready for Acceptance"))) {
result = 'Warning!!You are skipped Stage Deployment!!'
result
}
else
null
}




Thanks,

Venkat

This widget could not be displayed.

Suggest an answer

Log in or Sign up to answer
Community showcase
Published Aug 22, 2018 in Marketplace Apps

How a Marketplace app tech team is achieving gender diversity

Hello! My name is Genevieve Blanch, and I'm the Marketing Manager at RefinedWiki, creators of apps to give teams the tools to customize Atlassian platforms. Currently, 44% of the tech team at Re...

507 views 3 18
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you