It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

Creating a dropdown user macro

Hi All,

I'm in the middle of creating a user macro to have a dropdown selection box on a confluence page.

I would like the macro to be put anywhere on a page with the different selectable options to be input in the body of the macro.

The html for the macro is very simple although I'm not sure how to reference each line of the body in the macro.

For example, if I want a month selection box I want to be able to insert the macro on the page then within the body type:

January

February

March etc...

And in view mode it to work like a standard dropdown.

I have a checklist plugin that has an aspect called "checklist-select" which is essentially what I need, however, this only works within the checklist table.

Can anyone help on this?

Thanks

6 answers

1 accepted

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

It goes back to the first option because it does not save the entry anywhere.  I wrote a version that will let you save the entry, but you have to be running Confluence 5.6+, because it requires the new ContentProperties endpoint from the new REST API:

## @param DropdownId:title=Unique dropdown ID|type=string|required=true|default=1|desc=If more than one dropdown in page, change this to a unique name.
## @param Label:title=Label|type=string|desc=Enter dropdown label, if desired
#set ( $dropdownId = "" )
#set ( $dropdownId = "dropdown-" + $paramDropdownId )
#set ( $label = "" )
#set ( $label = $paramLabel )
#set ( $toplabel = "" )
#if ( $label == "" )
  #set ( $toplabel = "top-label" )
#end
#set ( $pageId = $content.id )
#set ( $options = $body.split("\n") )
<form class="aui $toplabel">
  <div class="field-group">
    #if ( $label != "" )
      <label for="$dropdownId">$label</label>
    #end
    <select class="select" id="$dropdownId" name="$dropdownId">
    #foreach ( $option in $options )
      #set ( $option = $option.trim().replaceAll('"', '' ) )  
      <option value="$option">$option</option>
    #end
    </select>
  </div>
</form>
<script>
AJS.toInit(function() {
  var canEdit = true;
  
  #if ( $permissionHelper.canEdit($userAccessor.getUserByName($req.remoteUser), $content) )
  jQuery("#$dropdownId").change(function() {
    var dropdownObject = this;
    jQuery.ajax({
      url: contextPath + "/rest/api/content/${pageId}/property/${dropdownId}",
      success: function(dropdownData) {
        dropdownData.value = jQuery(dropdownObject).val();
        dropdownData.version.number += 1;
        jQuery.ajax({
          contentType: 'application/json',
          type: 'PUT',
          url: contextPath + "/rest/api/content/${pageId}/property/${dropdownId}",
          data: JSON.stringify(dropdownData)
        });
      },
      error: function(response) {
        var dropdownData = {};
        dropdownData.key = "$dropdownId";
        dropdownData.value = jQuery(dropdownObject).val();
        jQuery.ajax({
          contentType: 'application/json',
          type: 'POST',
          url: contextPath + "/rest/api/content/${pageId}/property",
          data: JSON.stringify(dropdownData)
        });
      }
    });
  });
  #else
    canEdit = false;
  #end
  
  jQuery.ajax({
    url: contextPath + "/rest/api/content/${pageId}/property/${dropdownId}",
    success: function(dropdownData) {
      jQuery("#$dropdownId").val(dropdownData.value);
      if (!canEdit) {
        jQuery("#$dropdownId").prop( "disabled", true );
      }
    }
  });
});
</script>

EDIT: fixed bracket errors from when answer was imported from Atlassian Answers 

Luckily I'm on 5.6.3. This is perfect, thank you! I'm currently still trying to teach myself all this but this has helped me understand the mechanics of how this code works. Thanks again

Maybe its my installation of confluence, but what do you use to separate the options in the dropdown menu? Everything thats in the body of the macro is bundled together in one line.

This is great! How do you specify the items in the drop-down menu?

Sorry, I guess I didn't make this very clear in my answer.  You should include each of the options in the body of the macro each on their own line. So they should look like this:

option 1
option 2
option 3
etc.

And you should make sure one of the body options is selected when inserting the macro (Escaped is probably safest)

Like shakutin-il likes this

Awesome script. Is it possible to use this dropdown in a template and write something on the site depending on the choice you make. For example if i generate a new site via template and choose option1 the topic is "This is a page for Option 1"

We are using Confluence 5.9.12. That macro would be really great. But unfortunately, the changed Option is not saved. When i reload the page, the first Option is beeing showed.

What could be the Problem? In the log file is no entry that give some informations.

Thanks for your help.

Great! Thanks! It works.

Is it possible to set a width for dropdown field to make it narrower?

Is it possible to place a label above dropdown field?

I tried adding this macro but it just seems to output HTML instead of rendering anything, seemingly regardless of how I configure th user macro. I'm running Confluence 6.1.2

Thanks!

Hi Menso,

Did you figure out any solution ? I am running into the same issue. Doesn't works on 6.1.2

Did anyone figure out how to solve the issue where the macro just outputs the HTML instead of rendering it?

Thank-you!

Seems like the code above is corrupted. Just replace following:

&lt; with <

and

&gt; with >

and it should work fine.

Where I need to paste this code in Confluence-cloud?
In Insert markup-->and in the category of Insert choose conflunce-wiki or Markdown?

‏‏לכידה.PNG

Hi Eitan,

This is user macro code, not Markdown or Wiki Markup. Unfortunately user macros are not available in Confluence Cloud, but it would be theoretically possible to recreate in Confluence Cloud.

What do you mean by saying " it would be theoretically possible to recreate in Confluence Cloud" - Is there any way to do this or you recommend to buy add-ons like: ProForma, Forms for Confluence ?

Hello there,

it seems to be great code, but i cannot see how you create different options.

It always comes out as

"option 1option2 option3, when I enter

option 1

option 2

option 3

into the macro body.

 

Could someone explain my wrongdoing and light up my miserable life?

Thanks!

1 vote

Hi Andrew,

I was able to find these answers which may help you:

https://answers.atlassian.com/questions/274798

https://answers.atlassian.com/questions/15253

There are some tips and examples that can help smile

Cheers

Rodrigo

I did see these, they are not quite what I need. I'm looking to have a dropdown box on the page. And to change the options I edit the page and amend the macro body so that each line is a different option. Is that not possible?

Hi Andrew,

If you're just looking to see how to get each line, here's a simple user macro (I used "Escaped" for the output):

## @noparams
#set ( $lines = $body.split("\n") )
&lt;p&gt;
#foreach ( $line in $lines )
  ${line}, 
#end
&lt;/p&gt;

This looks like what I am after! How would I use this with a simple HTML dropdown?

As requested, with dropdown:

## @noparams
#set ( $lines = $body.split("\n") )
&lt;form class="aui top-label"&gt;
  &lt;div class="field-group"&gt;
    &lt;select class="select"&gt;
    #foreach ( $line in $lines )
      #set ( $option = $line.trim().replaceAll('"', '' ) )  
      &lt;option value="$option"&gt;$option&lt;/option&gt;
    #end
    &lt;/select&gt;
  &lt;/div&gt;
&lt;/form&gt;

Perfect! I had a play and created something similar but this seems to be a bit better. The only problem I'm having now is that whenever I go back to the page the selection has changed back to the first option. Any idea how to stop this?

I'm currently using the macro. The problem is whatever I put on the selection, it did not take effect or see by somebody else viewing the page. Unless I put a default value which makes no sense. any advise?

Hi Neil,

for a macro that actually saves the results in the page, please refer to the larger macro above on this same page smile

Hi all,

Free Plugin helped me to get the macro. Hope it helps others.

https://marketplace.atlassian.com/plugins/eps.focuspro.EasyDropdownMenu/server/overview 

Hello there,

it seems to be great code, but i cannot see how you create different options.

It always comes out as

"option 1option2 option3, when I enter

option 1

option 2

option 3

into the macro body.

 Could someone explain my wrongdoing and light up my miserable life?

Thanks!

My macro options look like the following in the page edit view

2018-06-21 10-09-26-User Macro Test - Confluence Testing - Confluence.png

My macro code looks like the following

## @param DropdownId:title=Unique dropdown ID|type=string|required=true|default=1|desc=If more than one dropdown in page, change this to a unique name.
## @param Label:title=Label|type=string|desc=Enter dropdown label, if desired
#set ( $dropdownId = "" )
#set ( $dropdownId = "dropdown-" + $paramDropdownId )
#set ( $label = "" )
#set ( $label = $paramLabel )
#set ( $toplabel = "" )
#if ( $label == "" )
#set ( $toplabel = "top-label" )
#end
#set ( $pageId = $content.id )
#set ( $options = $body.split("\n") )
<form class="aui $toplabel">
<div class="field-group">
#if ( $label != "" )
<label for="$dropdownId">$label</label>
#end
<select class="select" id="$dropdownId" name="$dropdownId" onchange="colourFunction()">
#foreach ( $option in $options )
#set ( $option = $option.trim().replaceAll('"', '' ) )
<option value="$option">$option</option>
#end
</select>
</div>
</form>
<script>
AJS.toInit(function() {
var canEdit = true;

#if ( $permissionHelper.canEdit($userAccessor.getUserByName($req.remoteUser), $content) )
jQuery("#$dropdownId").change(function() {
var dropdownObject = this;
jQuery.ajax({
url: contextPath + "/rest/api/content/${pageId}/property/${dropdownId}",
success: function(dropdownData) {
dropdownData.value = jQuery(dropdownObject).val();
dropdownData.version.number += 1;
jQuery.ajax({
contentType: 'application/json',
type: 'PUT',
url: contextPath + "/rest/api/content/${pageId}/property/${dropdownId}",
data: JSON.stringify(dropdownData)
});
},
error: function(response) {
var dropdownData = {};
dropdownData.key = "$dropdownId";
dropdownData.value = jQuery(dropdownObject).val();
jQuery.ajax({
contentType: 'application/json',
type: 'POST',
url: contextPath + "/rest/api/content/${pageId}/property",
data: JSON.stringify(dropdownData)
});
}
});
});
#else
canEdit = false;
#end

jQuery.ajax({
url: contextPath + "/rest/api/content/${pageId}/property/${dropdownId}",
success: function(dropdownData) {
jQuery("#$dropdownId").val(dropdownData.value);
if (!canEdit) {
jQuery("#$dropdownId").prop( "disabled", true );
}
}
});
});
</script>

Many thanks.

With this, life is a bliss now.

Hi @Dalectric,

 

I have copied your code exactly as it is above and it is great, but I am experiencing what others have already mentioned, that all of the options entered into the body comes out as a single entry in the dropdown. Is it down to some CSS differences or some other global setting?

Could you please help?

Many thanks,

Peter

I'm not sure why this is happening. What browser is this on?

Is each option on it's own line?

Can you paste in some screenshots of the macro and the result?

I'm using Chrome. see images:

Dropdown macro - edit.PNGDropdown macro - render.PNG

What is the text style used in the macro? For mine it is Preformatted (which I cannot change) and in yours it looks like Paragraph. Maybe this is the reason why?

2018-09-21 12-59-02-Edit User Macro - Confluence.png

Macro Body Processing is Unrendered for me

Thanks. I'll check these and will report back.

It works! Thank you. Both changes needed to get it to work. It has to be unrendered and the style has to be preformatted. Thanks again!

Hi @Dalectric
I have another question if you don't mind. I used the dropdown macro in the page properties section and created an index page on top of that (similar to the Product requirements templates). They render fine on the index page, but the values set in the dropdowns are a bit hit and miss; they change every time when I refresh the page.

I thought it might be because the dropdownId is unique to the page not to the space, hence it picks the values randomly from all of the pages. So I added the page title reference into the Id as well, hoping it would make it unique across the space. The macro itself still works, but the values now all over the place. This is the modified line:

#set ( $dropdownId = "" )
#set ( $dropdownId = $content.title + "-dropdown-" + $paramDropdownId )

Have you got an idea how to make this work?

Many thanks,

Peter

Hmm, interesting, I've not played with the macro that much, so haven't seen this issue yet. When I get some time I'll see if I can have a look.

One thing to try is maybe use the page ID number instead of the title?

I changed it to ID and it seems to be functioning well. I'll need to test it a bit more, but if I refresh the 'child' page after selecting a different value in the dropdown and then refresh the index page, the changes are coming through nicely. It works the other way round as well, changing the dropdown in the index page, refresh and open the child page, the values are updated correctly. So imho it is an awesome piece of macro. :) 

Thanks for your help.

I have copied your macro. And it works fine. 

Just wonder if it is possible to change color when you change the drop down value?

You have this colourFunction in your code, but not the function itself

onchange="colourFunction()

 Kristel

Great solution, thanks for sharing. And the info on parent/child via page properties is pretty cool, where updating one will update the other page. Thanks everyone.

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

Community showcase
Posted in Jira

Watch Slack + Atlassian's Webinar: “Transform cross-functional collaboration with Slack + Atlassian

Hi Atlassian Community! We recently partnered together with Slack on a webinar, “ Transform cross-functional collaboration with Slack + Atlassian ”. Building fast, growing exponentially: all...

31 views 0 2
Join discussion

Community Events

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

Find an event

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

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you