Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

There's all kinds of ECMAScript class library examples around but all of the ones I find show how to retrieve all list items (through SP.ClientContent) but how do you get the current list item? I'm trying to call some JavaScript through a custom ribbon button that's on the List display popup and pass the ID of the current item to a new URL.

share|improve this question

6 Answers 6

I use the following code when I solve exactly what you are asking about.

I don't like having js code inside my xml, but haven't found any good ways to include it without having it on all pages.

This code triggers a modal dialog which is opened with the selcted docuemnt(s) and current list as parameters. It also enables the buttons only when some items are selected.

  <?xml version="1.0" encoding="utf-8"?>
        <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
          <CustomAction Id="AddDocument.Script" 
           Location ="ScriptLink" 
            ScriptBlock="function OpenAddDialog() {
            var ctx = SP.ClientContext.get_current();
            var items = SP.ListOperation.Selection.getSelectedItems(ctx);
            var myItems = '';
            var k;

            for (k in items)
            {
              myItems += '|' + items[k].id;
            }

            var options = SP.UI.$create_DialogOptions();
            options.url = '~site/_layouts/myPage.aspx?items='+myItems+ '&amp;source=' + SP.ListOperation.Selection.getSelectedList();
            options.width = 1050;
            options.height = 600;
            //options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
            SP.UI.ModalDialog.showModalDialog(options);
            }

            function enableDisableButton() { 
                return CountDictionary(SP.ListOperation.Selection.getSelectedItems()) > 0; 
             }"/>
          <CustomAction Id="AddDocument" RegistrationType="List"
          RegistrationId="101" Location="CommandUI.Ribbon">
            <CommandUIExtension>
              <CommandUIDefinitions>
                <CommandUIDefinition Location="Ribbon.Documents.New.Controls._children">

                  <Button Id="Ribbon.Documents.New.Controls.AddDocument"
                  Alt="Add selected documents " Sequence="10"
                  Command="AddDocument" LabelText="Add document"
                  TemplateAlias="o2" />
                </CommandUIDefinition>
              </CommandUIDefinitions>
              <CommandUIHandlers>
                <CommandUIHandler Command="AddDocument"
                EnabledScript="javascript:enableDisableButton();"
                CommandAction="javascript:OpenAddDialog();" />
              </CommandUIHandlers>
            </CommandUIExtension>
          </CustomAction>
        </Elements>
share|improve this answer
1  
Sweet! SP.ListOperation.Selection is what we need here. –  Andrey Markeev Apr 13 '11 at 17:15
2  
No, this only gets you items if you select multiple items in the list. I'm looking for the current item that's shown in the DisplayForm.aspx popup when you click on an item. The .Selection property is null inside this dialog. –  Bil Simser Apr 13 '11 at 18:38

For every list form the ID of the selected item is in the query string where you can retrieve it using script. The ID parameter is used for the item. The List parameter for the list ID. This should facilitate you nicely.

Wouter

share|improve this answer
    
does that still work with showModalDialog() as it is an ajax request? –  djeeg Apr 15 '11 at 6:27
    
I think so yes. The modal dialog runs in an IFrame and scripts loaded into that IFrame will likely access that unique URL and not the URL of the parent frame. –  Wouter - SharePoint MVP Apr 15 '11 at 8:34
    
An example here: blog.pathtosharepoint.com/2009/01/18/… –  Christophe Apr 22 '11 at 6:13
up vote 20 down vote accepted

Looks like nobody really came up with the right answer. There are a lot of answers here but I eventually found what I was looking for.

Brage's answer is correct if I had a selection of items to work from. For this to work, you must enable item selection on the view and let the user select more than one item. SP.ListOperation.Selection will give you back a collection of list items which you can then display on a page or use as a dropdown or something.

Wouter's answer to use the query string works but it requires you to poke into the query string for the page and there's no native Javascript function to do that so you're parsing the window.location.href value. It's ugly but works although I haven't tried it with a modal dialog.

The real answer to get the currently selected item in a dialog is to use the URL tokens. The only "official" page that I found on MSDN that lists these is here:

http://msdn.microsoft.com/en-us/library/ms473643(v=office.12).aspx

(and that's a WSS 3.0 version page)

I couldn't find any page on the 2010 documentation with the list and the 2010 version of this page removes that section.

Others have blogged about it but it's somewhat obscure.

In any case, there are tokens you can use inside of your Elements.xml file as part of a CommandAction or UrlAction. So for example in my case I wrote:

<CommandUIHandler CommandAction="javascript:viewDialog({ItemId});"/>

Which would call this method in a JavaScript file I included in the solution:

function viewDialog(id) {
  var options = {
    url: "/sitename/Lists/ListName/ViewName.aspx?ID=" + id,
    width: 800,
    height: 600,
  };

  SP.UI.ModalDialog.showModalDialog(options);
}

This creates a modal dialog and displays the specific view I want filtered on the item id I pass in.

Thanks for the input everyone!

share|improve this answer
    
Good stuff Bil! One note is that the tokens only work if you put your script into an elements.xml file. Bit obvious, but hey :) –  Wouter - SharePoint MVP Apr 20 '11 at 12:15
    
You can have the script in a separate file and pass the tokens to it. Writing up a blog post on this right now ;) –  Bil Simser Apr 20 '11 at 12:42
    
I couldnt get this to work. It seems that the token is never resolved inside the CommandUIHandler's CommandAction attribute. Instead i used SP.ListOperation.Selection.getSelectedItems()[0].id –  Anders Rask Apr 27 '12 at 12:36

This may be too late for you, but i just had this same problem and did it as follows:

var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
var i;
var thisID;
var count=CountDictionary(items);// was the key point that was missing from other examples i saw

for (i=0,i<count;i++)
{
  thisID=items[i].id;
  // code that needs thisID
}
share|improve this answer
    
Thanks. Didn't know about the CountDictionary call which can be useful if you need to know the number of items. In my example I posted you can just use for(k in items) to loop through everything returned from getSelectedItems(ctx) –  Bil Simser Jun 24 '11 at 11:14
    
typo in the for loop in code example. Should be for (i=0;i<count;i++) –  barrypicker Jul 14 at 21:33

These techniques are silly.

On every SharePoint page there's a javascript context variable:

 _spPageContextInfo 
{
    webServerRelativeUrl : "/ProjectWeb",
    webLanguage : 1033,
    currentLanguage : 1033,
    webUIVersion : 4,
    pageListId : "{c1d7b89f-f07b-4e2e-b89c-76c315831d59}",
    pageItemId : 5,
    userId : 68,
    alertsEnabled : true,
    siteServerRelativeUrl : "/",
    allowSilverlightPrompt : "True"
} 

So if you are on /ProjectWeb/Pages/default.aspx

_spPageContextInfo.pageListId;   // list guid for Pages
_spPageContextInfo.pageItemId;   // ID for listitem

An example for versions page:

var options = {
    tite: "Versions",
    url: _spPageContextInfo.webServerRelativeUrl + "/_layouts/Versions.aspx?list="+ _spPageContextInfo.pageListId +"&ID="+ _spPageContextInfo.pageItemId,
    width: 800,
    height: 500,
};
SP.UI.ModalDialog.showModalDialog(options);
share|improve this answer
    
awesome. Why has no-one else been commenting on this on the web? Do you have a source for where you found this client side information? –  Brian Scott Mar 12 '12 at 14:06
2  
If you have customized the page with additional web parts, the aforementioned _spPageContextInfo might not carry the pageListId and pageItemId variables. In my case, I have customized EditForm.aspx to include other web parts (e.g. a list of related links corresponding to the item being edited). I suppose, until the user interacts with a specific web part, there can be no reason to assume a List or Item id and that is why it's omitted. –  bkwdesign Dec 19 '12 at 17:23
1  
Following on what @bkwdesign said, I've added additional webparts and I get undefined for the pageItemId value –  jasonscript Jun 25 at 3:54
    
While pageListId is available and populated, pageItemId is missing during debugging of SP 2013. –  barrypicker Jul 14 at 21:06

This should be what you're looking for: http://johnliu.net/blog/2012/2/3/sharepoint-javascript-current-page-context-info.html

I almost pulled my hair out trying to figure this same thing out! But I finally found out about the current page context info. Huge help!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.