J Tricks - Little JIRA Tricks
 

It is actually a follow-up post. A follow-up to the question Mizan asked in my last
post. Before you proceed, here is warning: Strictly for AJS novices, like me!

In this post, we are looking to prepopulate jira fields based on the current user's group. And we are gonna use AJS for the same!

Let us first split the problem into 3 pieces:

1. Get the current user
2. Get the groups of current user and check if the user belongs to a given group
3. Pre-populate the needed fields

With AJS, using Javascript in JIRA is damn easy. And with the introduction of REST services, getting information from the server is even easier. Let us attack the steps one by one.

1. Get the current user

Retrieving the current user is pretty easy, thanks to the following REST method: 

/rest/gadget/1.0/currentUser

It returns a JSON output of the following format:

{"username":"jobin","fullName":"Jobin Kuruvilla","email":"jobinkk@xxxx.com"}

Retrieving the user name from this using AJS is done using the jQuery's ajax method as shown:

function getCurrentUserName()
{
var user;
     AJS.$.ajax({
        url: "/rest/gadget/1.0/currentUser",
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data) {
            user = data.username;
        } 
     });
     return user;
}


For more information on ajax() method, have a look here.

2. Get the groups of current user and check if the user belongs to a given group

Now that we have the current user, we need to get the groups the user belongs to! Back to REST APIs and here is the method that you need:

/rest/api/2.0.alpha1/user?username=xxxx

Make sure the groups is expanded by appending &expand=groups at the end. Assuming jobin is the user name, here is the full URL:

/rest/api/2.0.alpha1/user?username=jobin&expand=groups

It returns the following JSON output:

{"self":"https://localhost:8080/rest/api/2.0.alpha1/user?username=jobin","name":"jobin","emailAddress":"jobinkk@xxxx.com","avatarUrl":"https://localhost:8080/secure/useravatar?size=large&ownerId=jobin","displayName":"Jobin Kuruvilla","active":true,"timeZone":"America/Los_Angeles","groups":{"size":3,"items":[{"name":"jira-administrators"},{"name":"jira-developers"},{"name":"jira-users"}]},"expand":"groups"}

Again, we use the ajax method to get the above output and extract the groups array from it as shown:

function getGroups(user)
{
var groups;
     AJS.$.ajax({
        url: "/rest/api/2.0.alpha1/user?username="+user+"&expand=groups",
        type: 'get',
        dataType: 'json',
        async: false,
        success: function(data) {
            groups = data.groups.items;
        } 
     });
     return groups;
}


Once the groups array is retrieved, checking for a given group is easy, isn't it?

function isUserInGroup(user, group){
    var groups = getGroups(user);
    for (i = 0; i < groups.length; i++){
         if (groups[i].name == group){
              return true;
         }
    }
    return false;
}

3. Pre-populate the needed fields

Over to Step 3. If the user is indeed in the given group, do whatever you want to! For example, you can pre-populate the decription as follows:

var user = getCurrentUserName();
if (isUserInGroup(user, 'jira-users')){
     AJS.$("#description").val('This is raised by a JIRA User!');
}


And if you are Mizan and you need to pre-populate the security level, make sure you have issue security schemes correctly configured and use the following snippet in place of description:

AJS.$("#security").val("10001");

where 10001 is the id of the appropriate securiyt level. And we are done! There might be an easier approach, but this isn't too bad, is it?

Attached is the full script in the end. Don't forget to have a look at the book ;)
checkgroups
File Size: 1 kb
File Type: checkgroups
Download File

 


Comments

Mizan
02/05/2012 10:01pm

Best tutorial for understanding AJS and REST . Thank you JTricks :)

Reply
J-Tricks
02/06/2012 5:33am

Thanks :) Btw, if you just need to get the current user and do something with it, you can use the query 'get' method like this:

<script type="text/javascript">
AJS.$.get("/rest/gadget/1.0/currentUser", function (data) {
alert ('User:'+data.username);
})
</script>

Reply
Dave
02/21/2012 5:29pm

Hi J-Tricks,

I am unsuccessfully trying to perform the following AJAX call in Jira while trying to use jQuerys autocomplete function. I was just wondering if you could point me in the right direction as to how to use AJS as you do above? Do i need to include a new dependency for AJS or anything like that? I should also point out that everything works in a local test webpage but doesnt in JIRA. Many thanks J-Tricks.

My code:

<script type="text/javascript">
$(function () {
$("#autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
url: "http://myurl",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{inputValue:\"" + request.term + "\"}",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
value: item
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$.ajax({
type: "POST",
url: "http://myurl",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{details:\"" + ui.item.label + "\"}",
success: function (data) {
document.getElementById('guid').value = data.d[0];
}
});
}
});
});
</script>

<input id="autocomplete" onclick="this.select();"/>

Reply
J-Tricks
02/22/2012 7:05pm

Did you try including the resources as follows?

#requireResource("com.atlassian.jira.gadgets:common")
#includeResources()

See http://www.j-tricks.com/1/post/2011/04/invoking-rest-services-from-gadgets.html for an example.

Reply
Dave
02/28/2012 12:55am

Hi J-Tricks,

Yes i have tried that and i still can't reference AJS. Do i need to include anything in the atlassian-plugin.xml?? could you perhaps provide an example of how you would use the jQuery.autocomplete if you were to try it?

Many thanks

Sebastian Wainer
07/16/2012 4:50am

hello J-Tricks,

thanks a lot for this tutorial. its working for jira 5.0 when i am using

JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, function (e, context)

for the createissue popup dialog, but if i try to do something like

for (i = 0; i < AJS.$("#security").length; i++){
if (AJS.$("#security").text == currentCustomerGroup){
alert(AJS.$("#security")[i].val());
break;
}

i have to learn that the data in the security level field is not ready when my script runs in the announcement banner.

what i need to do is to pre populate the security field according to the group in which the customer is, where i use the naming customer_name for the different customers.

Any suggestion how i can execute my script when the data in the field is ready?

Reply
J-Tricks
07/20/2012 4:41pm

Try adding the script in the description of the field under field configurations instead of adding it in the announcement banner.

Reply
Dan
06/26/2013 4:44am

Hi Sebastian,

I just wondered if you could the code that you are using in 5.0, as I am also trying to use this but can not seem to get this to work. My code is supplied further down the question list

Reply
Mizan
08/28/2012 5:11am

Hi JTricks ,

Can i get the user roles instead of user groups ? or is there a way to check for user roles in javascript ?
Thank you .

Reply
J-Tricks
08/28/2012 8:23am

Mizan,

You can use any REST API to retrieve information like the above. For roles, there is no direct REST API available in JIRA and hence you will have to develop one by your self.

Another option will be to use a combination of different APIs - first get projects, then find all roles in the project, find actors for roles and so on.

Will be a complex Javascript logic!

Reply
09/01/2012 11:46pm

Great tutorial on REST and AJS. Atlassian's documentation is rather hard to follow whereas this feels very easy for beginners.

Reply
Srinivas
10/08/2012 5:11pm

Hi Jobin, Could you please let me know if there any tutorials on the usage of AUI components?

Thanks

Reply
J-Tricks
10/08/2012 6:23pm

I usually find these pages useful.

https://developer.atlassian.com/display/AUI/Atlassian+User+Interface+%28AUI%29+Developer+Documentation
https://developer.atlassian.com/display/AUI/AUI+Components
http://docs.atlassian.com/aui/latest/demo-pages/

Hope it helps!

Reply
Srinivas
10/08/2012 7:59pm

Thanks for your reply. I would like to know more about the steps to be followed for configuring and working on AUI. I knew those links for the demo pages and the high level documentation. Can you tell me what dependencies need to include and what resources are required in the atlassian plugin.xml file?

04/09/2013 4:03am

I have found your post because I have been searching for some information about it almost three hours. You helped me a lot indeed and reading this your article I have found many new and useful information about this subject.

Reply
dhaval
05/08/2013 1:08am

Thanks for this tutorial.
I want to create user picker (auto-complete textbox) as like in JIRA in my velocity template. How it could be be achievable through AJS -REST service or best way to achieve user picker ?
Thank You

Reply
J-Tricks
05/08/2013 2:38pm

You can use the JIRA User picker custom field, right? If you want to customize, that custom field is the best place to start from.

Reply
dhaval
05/08/2013 10:58pm

Thanks for your comments. So, i just found "userpickersearcher" at below link:
https://developer.atlassian.com/display/JIRADEV/Custom+Field+Plugin+Module
Then, added user picker stuff (as below) in to atlassian-plugin .xml. Now, what should i add in velocity template to refer this custom field.
I have been using webwork module and related velocity template needs to include user picker.

stuff:
<customfield-searcher key="userpickersearcher" name="User Picker Searcher"
class="com.atlassian.jira.issue.customfields.searchers.UserPickerSearcher">
<description>
Allow to search for a user using a userpicker.
</description>

<!-- this template is used on the issue navigator search form -->
<resource type="velocity" name="search"
location="templates/plugins/fields/search-userpicker.vm" />
<!-- this element defines the valid custom field types for this searcher -->
<valid-customfield-type
package="com.atlassian.jira.plugin.system.customfieldtypes" key="userpicker" />
</customfield-searcher>

Thank You

J-Tricks
05/09/2013 4:41am

Well, that is different. You need to start with the custom field and not its searcher. See http://www.j-tricks.com/1/post/2010/08/custom-fields.html

06/24/2013 1:46am

Greetings to all the team! Your page is very good

Reply
Dan
06/25/2013 7:27am

great guide, although I cannot seem to get it to work with jira 5.1?

The only part I have changed is highlighted in red, that works on its own:

<script type="text/javascript">
var user = getCurrentUserName();
if (isUserInGroup(user, 'jira-users')){
AJS.$('#customfield_10350').parent().hide();

}
……………………………………………………………………………………………………………………

Reply
J-Tricks
06/26/2013 7:58am

It is because of the change in REST API url. Modify URL in getGroups method to have /api/2/user instead of /api/2.0.alpha1/user.

Modified method follows:

function getGroups(user)
{
var groups;
AJS.$.ajax({
url: "/rest/api/2/user?username="+user+"&expand=groups",
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
groups = data.groups.items;
}
});
return groups;
}

Reply
Dan
06/26/2013 8:36am

Thank you for your reply I have update the code and it is now working.

Very much appreciated.

06/26/2013 5:14am

I have no previous experience in jquery and AJAX. Is there any other method to extract the username, I mean other than the one you specified here? Can you please explain it in a bit more detail? Thanks in advance.

Reply

Your comment will be posted after it is approved.


Leave a Reply


J tricks - Little JIRA Tricks