Question

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.

Was it helpful?

Solution 2

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!

OTHER TIPS

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);

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>

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
}

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

As @Bil mentions, ItemId can be retrieved using Url tokens. However, I would like to differ on this statement

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.

I have tested below two native JavaScript functions in SP 2010 and SP 2013 and both of them are able to read query string values.

GetUrlKeyValue('ID')

JSRequest.EnsureSetup();
JSRequest.QueryString['ID']

Moreover, SP 2013 has an object named WPQ2FormCtx and it also holds the ID of the current item in the Display/Editform:

WPQ2FormCtx.ItemAttributes.Id

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top