Archive for September 10, 2013

SharePoint 2013: Programmatically add Related Items

The Task Content Type in SharePoint 2013 has a cool field named Related Items. Although there is some information about how to add this Field to other custom lists, there is no information on how to populate this field other then using the UI.

http://sampathnarsingam.blogspot.nl/2013/02/sharepoint-2013-related-items-site.html

Lucky for us this is quite simple! I will be using the JavaScript Object Model for this, but I’m sure this will be similar for the other models.

Console App to the Rescue

Since the Field Type of this column got me nowhere I just wanted to know the plain value of a Task that already had Related Items. It appeared to be a string[] containing JSON objects of related items according to this format:

[{“ItemId”:id, “WebId”:”WebGUID”, “ListId”:”ListGUID”}]

RelatedItemsValue

To my surprise I was able to put this literal string into the field using JavaScript Object Model. Nice! But the key is to first Create the Task and then Update it with the Related Items.

JavaScript Object Model

To test this I created a new Task using the value I got back from my Console App. Here’s the code:

var ctx = SP.ClientContext.get_current();
var taskList = web.get_lists().getByTitle('Tasks');
var taskInfo = new SP.ListItemCreationInformation();
var task = taskList.addItem(taskInfo);
task.set_item('Title', 'Appicon.png');
task.set_item('Body', 'Do some work for this item');
task.update();

ctx.load(task);
ctx.executeQueryAsync(function(){
task.set_item('RelatedItems', '[{"ItemId":1, "WebId":"c88c2b90-c2b1-4de4-9a05-ee109412152d", "ListId":"7be848a2-c703-47ef-8403-7d8fbf9e951c"}]');
task.update();
ctx.load(task);
ctx.executeQueryAsync(function(){
//Success
}, function(sender, args){
//2nd Fail
});
}, function(sender, args){
//Fail
});

Result

Opening the Task I created we can see the Related Items pointing to AppIcon.png which is just a picture in a Picture Library. Pretty cool huh!

RelatedItemsResult