Search code examples
javascriptrestsharepointcsom

How to retrieve metadata of document set using JavaScript


In my SharePoint site I have document sets with some metadata (Budget, Client Name, City ..). I want to change the default look of doc-set homepage. I want to retrieve the metadata of the current document set, show it in a content editor web part.

How do I retrieve current doc set metadata using JavaScript and based on the ID of the doc set?


Solution

  • Using the Document Set Properties web part

    First, keep in mind that there is already a web part that automatically displays metadata from the current document set. This web part is called "Document Set Properties" and can be found in the "Document Sets" category of web parts.

    The fields that it displays can be configured by navigating to Library Settings, clicking the name of your Document Set content type under Content Types, and clicking "Document Set Settings."

    Using REST or JSOM instead

    If for some reason that web part is inadequate for your purposes, you can use the REST API or JavaScript client side object model to retrieve metadata about the current document set. You can obtain the ID of the current document set from the "ID" parameter in the query string section of the URL.

    SharePoint provides a handy GetUrlKeyValue() method to easily obtain query string parameters.

    REST

    var itemId = GetUrlKeyValue("ID");
    var listGuid = GetUrlKeyValue("List");
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/_api/lists('"+listGuid+"')/items("+itemId+")");
    xhr.setRequestHeader("accept","application/json;odata=verbose");
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                var item = JSON.parse(xhr.responseText).d;
                var title = item.Title;
                var desc = item.DocumentSetDescription;
                // You can retrieve any other properties here as necessary
            }else{
               alert("error "+xhr.status+": "+xhr.responseText);
            }
        }
    };
    xhr.send();
    

    JSOM

    SP.SOD.ExecuteOrDelayUntilScriptLoaded(function(){
        var listGuid = GetUrlKeyValue("List");
        var itemId = GetUrlKeyValue("ID");
        var clientContext = new SP.ClientContext();
        var item = clientContext.get_web().get_lists().getById(listGuid).getItemById(itemId);
        clientContext.load(item);
        clientContext.executeQueryAsync(
            function(){
                 var title = item.get_item("Title");
                 var desc = item.get_item("DocumentSetDescription");
                 // You can retrieve any other properties here as necessary
            },
            function(sender,args){
                alert(args.get_message());
            }
        );
    },"sp.js");