Creating custom field with custom logic

All custom fields that come out of the box with JIRA have predefined purposes, such as text field, which allows users to type in some simple text. It will often be useful to have a specialized custom field that does exactly what you need. Unfortunately, this often requires custom development efforts.

However, there is an add-on that provides a custom field type that lets you use Groovy scripts to power its logic.

In this recipe, we will look at how to create a custom field that uses a Groovy script to display the total number of comments on any given issue.

Getting ready

For this recipe, we need to have the Script Runner add-on installed. You can download it from the following link or install it directly from the Universal Plugin Manager at https://marketplace.atlassian.com/plugins/com.onresolve.jira.groovy.groovyrunner.

You may also want to get familiar with Groovy scripting at http://groovy.codehaus.org.

How to do it…

Creating a scripted field is a two-step process. We first need to create an instance of the custom field in JIRA and then add the script to it:

  1. Log in to JIRA as a JIRA administrator.
  2. Navigate to Administration | Issues | Field Configurations.
  3. Click on the Add Custom Field button and select Advanced from the dialog box.
  4. Scroll down and select Scripted Field from the list, and click on Next, as shown in the following screenshot:
    How to do it…
  5. Name our new custom field Total Comments, and add it to the appropriate screens.
  6. Navigate to Add-ons | Script Fields.
  7. Click on the Edit link for the Total Comments field.
  8. Enter the following Groovy script in the script text box:
    import com.atlassian.jira.ComponentManager
    
    def commentManager = ComponentManager.getInstance().getCommentManager()
    
    def numberOfComments = commentManager.getComments(issue).size()
    
    return numberOfComments ? numberOfComments as Double : null
  9. Select Number Field for Script Template, and click on OK as shown in the following screenshot:
    How to do it…

How it works…

The scripted field type is an example of what is called calculated custom field type. The calculated custom field type is a special custom field that derives (calculates) its value based on some predefined logic, in this case, our Groovy script. Every time the field is displayed, JIRA will recalculate the field's value so it is always kept up to date.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset