Creating and Updating Sharepoint 2010 Lists from the Other Side of the Aisle or Isle
Six months ago, I wrote a tip entitled "How to Create, Write to, and Read From Sharepoint 2010 Lists with C#." You can gawk at it here
If you need or prefer to work as much with client code (Javascript/jQuery) as possible (as opposed to working as much with the
code-behind C# as possible, as that previous tip had as its premise), you might enjoy this tip, which demonstrates the former,
Javascript-centric methodology.
The first thing you have to do in any situation is to follow Bruce Springsteen's musical advice and "give it a name." So first
give your List a name. To do so, put this within your WebPart class (prior to the constructor or any other methods):
public string listTitle = "dPlatypus";
Give your list whatever name you want, but preferably something descriptive and unique.
Since we are going to (conditionally - that is, once and once only) create a Sharepoint list, write to the list and read from
it, we should start by defining the structure of the list itself. We do this by creating a separate class, such as this one (in C#,
in the *.ascx.cs file):
public class PostTravelFormFields
{
public DateTime ptli_formFilledOut { get; set; }
public string ptli_TravelersName { get; set; }
public string ptli_TravelersEmail { get; set; }
public string ptli_TravelersPhone { get; set; }
public string ptli_TravelersMailstop { get; set; }
public string ptli_TravelersStreetOrPO { get; set; }
public string ptli_TravelersDestination { get; set; }
public string ptli_BusinessPurpose { get; set; }
public DateTime ptli_dtDeparture { get; set; }
. . .
}
Of course, you will have different members of your list.
Now for the interesting parts, or the "nitty-gritty" (Yeah, Dirt Band!). The "rubber meats the road" when the user does
something with the data, like so (this is jQuery):
var _TravelersName;
var _TravelersEmail;
var _TravelersPhone;
var _TravelersMailstop;
var _TravelersStreetOrPOBox;
var _TravelersDestination;
var _BusinessPurpose;
var _dtDeparture;
. . .
_TravelersName = $('#travelername').val();
_TravelersEmail = $('#traveleremail').val();
_TravelersPhone = $('#travelerphone').val();
_TravelersMailstop = $('#travelermailstop').val();
_TravelersStreetOrPOBox = $('#travelerstreetorpobox').val();
_TravelersDestination = $('#travelersdestinations').val();
_BusinessPurpose = $('#ucbusinesspurpose').val();
_dtDeparture = $('#travelersdeparturedate').val();
upsertPostTravelListItemTravelerInfo1();
The values such as "#travelername" reference html elements with the corresponding IDs, of course. And here's the Upsert jQuery method called from above:
function upsertPostTravelListItemTravelerInfo1() {
var clientContext = SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');
this.website = clientContext.get_web();
currentUser = this.website.get_currentUser();
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
var travelersEmail = $('#traveleremail').val();
var departureDate = $('#travelersdeparturedate').val();
setListItemID(currentUser, travelersEmail);
setTimeout(function () {
var b = 42;
}, 3000);
if (listId === '') {
listId = this.oListItem.ID;
}
oListItem.set_item('Title', currentUser + '_' + travelersEmail + '_' + departureDate);
oListItem.set_item('ptli_formFilledOut', $('#formfilledout').val());
oListItem.set_item('ptli_preparerEmail', currentUser);
oListItem.set_item('ptli_TravelersName', $('#travelername').val());
oListItem.set_item('ptli_TravelersEmail', travelersEmail);
oListItem.set_item('ptli_TravelersPhone', $('#travelerphone').val());
oListItem.set_item('ptli_TravelersMailstop', $('#travelermailstop').val());
oListItem.set_item('ptli_TravelersStreetOrPO', $('#travelerstreetorpobox').val());
oListItem.set_item('ptli_TravelersDestination', $('#travelersdestinations').val());
oListItem.set_item('ptli_BusinessPurpose', $('#ucbusinesspurpose').val());
oListItem.set_item('ptli_dtDeparture', departureDate);
oListItem.set_item('ptli_dtReturn', $('#travelersreturndate').val());
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this,
this.onQueryFailed));
}
Here is the helper function to set the ListItemId:
function setListItemID(username, payeename) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ptli_TravelersEmail\' /><Value Type=\'Text\'>' + payeename
+ '</Value></Eq></Where></Query></View>');
var oListItems = oList.getItems(camlQuery);
clientContext.load(oListItems);
clientContext.executeQueryAsync(
Function.createDelegate(this, function () {
var arrayListEnum = oListItems.getEnumerator();
var ids = [];
while (arrayListEnum.moveNext()) {
var listItem = arrayListEnum.get_current();
ids.push(listItem.get_id());
}
if (ids.length > 0) {
listId = ids[0];
}
else {
listId = '';
}
}),
Function.createDelegate(this, function (sender, args) {
alert("Whoops: " + args.get_message() + " " + args.get_stackTrace());
})
);
}
There is some more C# code that I have retained, even in this Javascript-centric tip. Specifically, it is to conditionally
create the list (also in the *.ascx.cs file, like the list definition class):
private void ConditionallyCreateList()
{
SPWeb site = SPContext.Current.Web;
site.AllowUnsafeUpdates = true;
if (site.Lists.TryGetList(listTitle) != null) return;
SPListCollection lists = site.Lists;
SPListTemplateType listTemplateType = new SPListTemplateType();
listTemplateType = SPListTemplateType.GenericList;
string listDescription = "This list retains vals inputted for the Post Travel form";
Guid ListId = lists.Add(listTitle, listDescription, listTemplateType);
SPList list = site.Lists[ListId];
list.OnQuickLaunch = true;
list.Fields.Add("ptli_listCollectionId", SPFieldType.Guid, false);
list.Fields.Add("ptli_formFilledOut", SPFieldType.DateTime, false);
list.Fields.Add("ptli_TravelersName", SPFieldType.Text, false);
list.Fields.Add("ptli_TravelersEmail", SPFieldType.Text, false);
list.Fields.Add("ptli_TravelersPhone", SPFieldType.Text, false);
list.Fields.Add("ptli_TravelersMailstop", SPFieldType.Text, false);
list.Fields.Add("ptli_TravelersStreetOrPO", SPFieldType.Text, false);
list.Fields.Add("ptli_TravelersDestination", SPFieldType.Text, false);
list.Fields.Add("ptli_BusinessPurpose", SPFieldType.Text, false);
list.Fields.Add("ptli_dtDeparture", SPFieldType.DateTime, false);
. . .
Now to update the existing list, the assignment code is of the same ilk; the posting code only slightly differs:
function upsertPostTravelListItemTravelerInfo2() {
var clientContext = SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('PostTravelFormFields');
this.oListItem = oList.getItemById(listId);
. . .
As you can see, the existing list is used, so that the same list already inserted into is updated, as opposed to a new one. listId is a var that is defined and used this way:
var listId;
. . .
this.oListItem = oList.addItem(itemCreateInfo);
. . .
if (listId === '') {
listId = this.oListItem.ID;
}
this.oListItem = oList.getItemById(listId);
And so the first time (the insert), the generated and returned id is used; after that, that same saved value is used, so that the list is being updated.
Und damit basta (that's a German sermon, not a Russian cussin')
That should work (it does for me); however, programming being what it is, and perhaps Sharepoint in particular, you will probably run into some problems - IOW, don't expect it to work perfectly the first time. So remember: google and/or bing are your friends.