I am trying to access the ID of Library using client-side object model in SharePoint 2013. But I am getting error as:
The property or field 'Id' has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Below is my code:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var items = SP.ListOperation.Selection.getSelectedItems(context);
var currentLibrary = web.get_lists().getById(SP.ListOperation.Selection.getSelectedList(context));
context.load(currentLibrary, 'id'); // Tried with 'Id' but still throws error
console.log(currentLibrary);
console.log("currentLibrary.get_id = " + currentLibrary.get_id()); // THROWS ERROR!
What am I doing wrong here?
The error:
The property or field 'Id' has not been initialized. It has not been requested…
occurs since List object has not been requested.
Use SP.ClientContext.executeQueryAsync method to execute the current pending request asynchronously on the server
A working example:
var context = SP.ClientContext.get_current();
var web = context.get_web();
var listId = SP.ListOperation.Selection.getSelectedList(context);
var list = web.get_lists().getById(listId);
context.load(list, 'Id'); //tell SharePoint to load List Id property
context.executeQueryAsync( //submit query to the server
function(){
console.log("ID:" + list.get_id()); //process result in success callback
},
function(sender,args){
console.log(args.get_message()); //handle error in error callback
}
);