Extract Information from the Grid using the Java API
Introduction
This article shows an example of how you can extract the grid data using the API and a scripted field in Jira.
The scripted field is a custom field, provided by the Script Runner. Check the example below.
To save the sum of the numbers in the grid column as a value of another custom field.
Scripted field script
The script below helps to create a scripted custom field that calculates the sum of all numbers in the specified column of the TGNG grid.
Configuration:
tgngCustomFieldName - the name of the TGNG grid custom field that will be used for calculation
columnIdToSum - a column identifier(a unique variable to identify the column) which will be used to get data for the summary calculation
You need to change the grid custom field name and column ID in the script as below:
// configuration (update it to match your JIRA settings)
String tgngCustomFieldName = "TGNG Grid";
String columnIdToSum = "summary";
scriptedFieldSum.groovy
import com.atlassian.crowd.embedded.api.User;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.plugin.PluginAccessor;
import com.atlassian.jira.user.ApplicationUser;
import org.apache.log4j.Logger;
// set up logger
Logger log=Logger.getLogger("com.idalko.scripts");
// get an issue
String tgngCustomFieldName = "TGNG Grid"; //Change the grid custom field name to relevant one
String columnIdToSum = "price"; //Change the column ID to the relevant one
// get TGNG custom field
CustomFieldManager customFieldManager = ComponentAccessor.getOSGiComponentInstanceOfType(CustomFieldManager.class);
CustomField tgngCustomField = customFieldManager.getCustomFieldObjectsByName(tgngCustomFieldName).get(0);
Long tgngCustomFieldId = tgngCustomField.getIdAsLong();
ApplicationUser applicationUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser();
// read grid data
PluginAccessor pluginAccessor = ComponentAccessor.getPluginAccessor();
Class apiServiceClass = pluginAccessor.getClassLoader().findClass("com.idalko.tgng.jira.server.api.GridService");
def gridFieldData = ComponentAccessor.getOSGiComponentInstanceOfType(apiServiceClass);
def callResult = null;
try {
callResult = gridFieldData.readFieldData(issue.getId(), tgngCustomFieldId, applicationUser, null);
} catch (Exception e) {
log.error(e.getMessage())
}
def gridRows = callResult.getRows();
Double sum = 0;
for (row in gridRows) {
def column = row.getColumns().get(columnIdToSum);
sum += column.toDouble()
}
return sum;