J tricks - Little JIRA Tricks
  • Home
  • Plugins ↓
    • JQL Tricks Plugin
      • JQL Tricks Plugin - Cloud
        • JQLT Cloud Installation
        • JQLT Cloud Configuration
        • JQLT Cloud Usage
        • JQLT Cloud License
        • JQLT Cloud FAQ
      • JQL Tricks Plugin - DC
        • JQLT DC Installation
        • JQLT DC Configuration
        • JQLT DC Usage
          • JQLT Issue Functions
          • JQLT Subtask Functions
          • JQLT Links Functions
          • JQLT Development Functions
          • JQLT Worklog Functions
          • JQLT Project Functions
          • JQLT Component Functions
          • JQLT Version Functions
          • JQLT Group Functions
          • JQLT User Functions
          • JQLT Date Functions
        • JQLT DC License
        • JQLT DC FAQ
        • JQLT DC Known Issues
        • JQLT DC Performance
      • JQL Tricks Cloud Migration
    • Simplified Planner
      • J-Planner Installation
      • J-Planner Configuration
      • J-Planner Usage
        • Creating a plan
        • Editing a plan
        • Deleting a plan
        • Viewing a plan
        • Modifying a plan
      • J-Planner FAQ
    • Atla-Search Plugin
      • Atla-Search Installation
      • Atla-Search Configuration
      • Atla-Search Usage
      • Atla-Search License
      • Atla-Search FAQ
    • Copy to subtask Plugin
    • All Plugins
  • Tutorials
  • The Book
  • Contact Us
  • Home
  • Plugins ↓
    • JQL Tricks Plugin
      • JQL Tricks Plugin - Cloud
        • JQLT Cloud Installation
        • JQLT Cloud Configuration
        • JQLT Cloud Usage
        • JQLT Cloud License
        • JQLT Cloud FAQ
      • JQL Tricks Plugin - DC
        • JQLT DC Installation
        • JQLT DC Configuration
        • JQLT DC Usage
          • JQLT Issue Functions
          • JQLT Subtask Functions
          • JQLT Links Functions
          • JQLT Development Functions
          • JQLT Worklog Functions
          • JQLT Project Functions
          • JQLT Component Functions
          • JQLT Version Functions
          • JQLT Group Functions
          • JQLT User Functions
          • JQLT Date Functions
        • JQLT DC License
        • JQLT DC FAQ
        • JQLT DC Known Issues
        • JQLT DC Performance
      • JQL Tricks Cloud Migration
    • Simplified Planner
      • J-Planner Installation
      • J-Planner Configuration
      • J-Planner Usage
        • Creating a plan
        • Editing a plan
        • Deleting a plan
        • Viewing a plan
        • Modifying a plan
      • J-Planner FAQ
    • Atla-Search Plugin
      • Atla-Search Installation
      • Atla-Search Configuration
      • Atla-Search Usage
      • Atla-Search License
      • Atla-Search FAQ
    • Copy to subtask Plugin
    • All Plugins
  • Tutorials
  • The Book
  • Contact Us

Some AJS Tricks!

2/5/2012

41 Comments

 

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

41 Comments
Mizan
2/5/2012 05:01:14 pm

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

Reply
J-Tricks
2/6/2012 12:33:45 am

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
2/21/2012 12:29:54 pm

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
2/22/2012 02:05:00 pm

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
2/27/2012 07:55:28 pm

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
7/16/2012 12:50:14 am

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
7/20/2012 12:41:46 pm

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

Reply
Dan
6/26/2013 12:44:35 am

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
8/28/2012 01:11:11 am

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
8/28/2012 04:23:02 am

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
concerto49 link
9/1/2012 07:46:31 pm

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

Reply
Srinivas
10/8/2012 01:11:59 pm

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

Thanks

Reply
J-Tricks
10/8/2012 02:23:51 pm

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/8/2012 03:59:27 pm

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?

executive drug rehab link
4/9/2013 12:03:43 am

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
5/7/2013 09:08:46 pm

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
5/8/2013 10:38:30 am

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
5/8/2013 06:58:37 pm

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
5/9/2013 12:41:58 am

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

Christina link
6/23/2013 09:46:38 pm

Greetings to all the team! Your page is very good

Reply
Dan
6/25/2013 03:27:03 am

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
6/26/2013 03:58:35 am

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
6/26/2013 04:36:52 am

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

Very much appreciated.

windows phone support link
6/26/2013 01:14:23 am

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
sobstel link
8/13/2014 02:11:27 am

Using /rest/api/latest/myself?expand=groups is quicker I think.

Reply
J-Tricks
8/14/2014 01:37:29 am

Thanks. Seems it came in the later version. Really useful :)

Also, AJS.params.loggedInUser gets you the current user, if you need it for something else.

Reply
Asif khan link
9/19/2014 06:41:27 pm

Hi Jtricks,

Is there any AJAX call I can use to get all the teams the current logged in user belongs to?

Thank You,
Asif

Reply
J-Tricks
9/20/2014 02:07:21 am

You can do this:

/rest/api/2/user?username="+AJS.params.loggedInUser+"&expand=groups

Checkout the getGroups above.

Reply
Asif Khan link
9/20/2014 06:58:42 am

Hi Jtricks,

The link you gave on the above link looks like it will return the groups the user belongs to. But I need the teams. Is the any AJAX link to get teams as well? If not , can I somehow use the above AJAX link for groups , to get the teams?

Best Regards,
Asif

J-Tricks
9/21/2014 04:39:37 am

What do you mean by teams? JIRA doesn't have the concept of a team. Maybe you are using a plugin?

Asif Khan link
9/21/2014 04:57:15 pm

Hi,

I am using the Tempo timesheet plugin. On any issue/ticket page, you can see tempo tab(dropdown). When you click on it, you get an option manage teams in the dropdown. You can create teams and add users or groups to various teams.
Now I want make an AJAX call from a javascript which brings me the team information of a logged in user, just like we did for groups. But I could not find any url/link for this. Kindly help if you have any inputs.

Thank You,
Asif

J-Tricks
9/23/2014 01:32:59 am

You need to check the plugin documentation to find out if they have a method that exposes it.

Or use Firebug or something to look into the network calls when the plugin is used ;)

Asif Khan
10/27/2014 09:22:32 pm

Hi ,

I tried using the fire bug to get the network calls and also the documentations, but none helped. I was wondering if you know any way to get the teams. For an AJAX call, I will need the url which I am not able to find.

Thanks in advance.

Best Regards,
Asif

Reply
J-Tricks
10/28/2014 02:13:29 am

/rest/tempo-teams/1/team will get you teams.
/rest/tempo-teams/2/team/{teamId}/member will get you the members
/rest/tempo-teams/2/team/1/member?type=USER if you want just the users
/rest/tempo-teams/2/team/1/member?type=GROUP if you just want the groups in the team.

Reply
Asif Khan
10/29/2014 01:29:22 am

Hi J-Tricks,

Thanks alot for the above url.
I tested all the four url , but unfortunately only the first one(url to get the teams) returned me the data.The other three didnot.
I want to know is there any forum or blog from where you got these urls or you created them ? Did all the four url returned you the data when you tested them?

Thanks again for your help so far.

Best Regards,
Asif

Asif Khan
10/29/2014 01:32:11 am

I used the url; /rest/tempo-teams/2/team/{2}/member
in the ajax call, where 2 is the ID of the team.But it didnot help. But the first url works.

J-Tricks
10/30/2014 03:00:35 pm

Yes, all the 4 returned data for me. Maybe the name space (2 in this case) is different for the version of the plugin that you have.

You might want to use "Firebug" or something to figure that out.

bash
11/16/2015 07:50:54 am

Hi J-Tricks,

I want to identify all the users who are NOT in the admin group and redirect them to another page while maintenance work is going on.

And after the maintenance activity is finished I want them to be able to access the server.

Reply
J-Tricks
11/16/2015 01:40:43 pm

You can tweak the above javascript and add it in the announcement banner to do the redirection when a user is not in the admin group.

Remove the javascript once the maintenance is over.

Reply
J-Tricks
11/16/2015 01:41:26 pm

Having said that, our recommendation would be to use Apache to serve the maintenance page and do the redirection ;)

Sourav Basak link
3/17/2016 02:35:43 pm

This information is quite informative and very useful. For a upcoming web developer this would be a good choice to being with code.
Every developer should follow this technique for accurately developing their web items.
Thanks for sharing this tips. This will gain the next level of web interface for creating the enough UI more creative.

--
Regards,
Sourav Basak [Blogger, Entrepreneur, Thinker]
http://www.namasteui.com

Reply

Your comment will be posted after it is approved.


Leave a Reply.

    Enter your email address:

    Author

    Jobin Kuruvilla - Works in Adaptavist as Head of DevOps Professional Services. 

    Author of JIRA Development Cookbook and JIRA 5.x Development Cookbook.


    RSS Feed

    Categories

    All
    Acive Objects
    Ajs
    Book
    Components
    Condition
    Custom Fields
    Customization
    Events
    Gadgets
    Javascript
    Jql
    Listener
    Mail
    Permissions
    Plugin Framework
    Post Function
    Properties
    Remote Invocation
    Reporting
    Rest
    Scheduled Tasks
    Search
    Services
    Soap
    Summit
    User Interface
    Validator
    Webwork Actions
    Workflow

    Archives

    October 2016
    August 2016
    March 2016
    January 2016
    December 2015
    May 2014
    December 2013
    November 2013
    July 2013
    June 2013
    April 2013
    October 2012
    September 2012
    August 2012
    July 2012
    May 2012
    March 2012
    February 2012
    January 2012
    December 2011
    November 2011
    June 2011
    May 2011
    April 2011
    March 2011
    February 2011
    January 2011
    November 2010
    October 2010
    September 2010
    August 2010

SUPPORT
APPS
TUTORIALS
THE BOOK
© J-Tricks