How I went about creating two related lists using JavaScript, Client Object Model and SharePoint 2010-Part1

I was struggling with how I could create two lists in SharePoint  2010 that were related.

Scenario: Let’s say that you want to have a list of meetings (we will call it MeetingsList), with each meeting having the potential of unlimited number of attendees. How can I do this in SharePoint? It is not possible to have Attendee-1 to Attendee-∞ (infinity) as fields in the MettingsList. I needed to move the attendees to their own list (we will call it AttendeeList). But how do I related the attendees to the meeting?

My work around: The trick was that I needed to know the MeetingsList item’s ID before I created the related attendees. I could not figure a way to get that ID until after the MeetingsList item was saved. The work around that I came up with was that I would create the item when a person clicked the “new” button, and then redirect them to EDIT the newly created item. Then I could add an item to the AttendeeList with ID of the current item being edited in the MeetingsList. Hope that makes sense. Steps and code:

  • Create a list that contains the meeting specifics – MeetingsList
  • Create a second list that will contain the attendees – AttendeeList
  • Use my Delegate Control method to insert JavaScript (code kept in a document library) into  the top of any page as described here
  • Add the following to the top of the NewForm.aspx page:
$(document).ready(function() {
	ExecuteOrDelayUntilScriptLoaded(createListItem,"SP.js");
});
function createListItem() {
    var clientContext = SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('MeetingsList');
    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);
    oListItem.update();
    clientContext.load(oListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
    }

function onQuerySucceeded() {
window.location.href = "/Lists/MeetingsList/EditForm.aspx?ID="+ oListItem.get_id();
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

All this Client Object Model code does is create a new item in the MeetingList list, and then redirect the browser to edit that item. Now, on the EditForm.aspx page, I know the item ID of the item I am editing and I can use this ID to create a new related item in the AttendeeList. Next steps are in part 2.

Comments are closed.