Home > SharePoint 2010, Visual Studio 2010 > Walkthrough 4: Accessing List Data using the JavaScript Client OM

Walkthrough 4: Accessing List Data using the JavaScript Client OM

 

Exercise Duration: 30 minutes

Exercise Overview 

This example illustrates how to use the ECMAScript client side object model to update and read list data dynamically. Also shown is how to use the new Dialog API’s from client side script.

Feature Overview

The JavaScript client side object model allows JavaScript developers access to SharePoint objects such as Site, Web and List (and more) from client side JavaScript. 

Task 1: Create a new Empty Project and add a web part. 

1. Open Visual Studio 2010 from the Start | Programs | Visual Studio 2010 menu.

2. Create a new project by using File | New Project.

3. Pick the SharePoint | 2010 templates.

4. From the SharePoint | 2010 templates select the Visual Web Part template.

5. Use ScriptOMExample as the name.

6. Set the location to be C:\SPHOLs.

7. Press OK to create the project.  

 

image

8. On the SharePoint Customization Wizard dialog, type the address of the site you want to deploy to, and select to deploy this as a farm solution.

9. Click Finish to proceed.

image

  

10. In the Solution Explorer expand the VisualWebPart1 item, and open VisualWebPart1.webpart by double-clicking on it.

a. Set the value of title element to: ScriptOMPart Title

b. Set the value of description element to: ScriptOMPart Description

 

image

Task 2: Add scripting code to access and render SharePoint list data.

1. In the Solution Explorer, open the VisualWebPart1Control.ascx by double-clicking on it.  Add the following the following markup code at the bottom of the file.

 

<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" Localizable="false" LoadAfterUI="true" />  

 

<script language="ecmascript" type="text/ecmascript">

 

</script>

 

2. Add the following JavaScript code within the Script block (before the closing </script> tag).

 

 

This code declares important variables our code will use later on and adds our Initialize() function to be called after all of the SharePoint client side objects have loaded.

/* SharePoint list names */

var ContactsListName = "Contacts List";

var CompanyListName = "Company List";

 

/* SharePoint list field names */

var CompanyNameField = "Title";

var CompanyPhoneField = "Company_x0020_Phone_x0020_Number";

var CompanyDescriptionField = "Company_x0020_Description";

var ContactFirstNameField = "First_x0020_Name";

var ContactTitleField = "Title";

var ContactLastNameField = "Last_x0020_Name";

var ContactEmailField = "E_x002d_Mail";

var ContactCompanyListField = "Company_x0020_List";

 

/* List objects */

var contactsList;

var companyList;

 

/* variable to hold list items from the contactsList */

var contacts;

 

/* client context object – used to access SharePoint data */

var context;

 

/* web (SPWeb) that our page is running on */

var web;

 

/* variable to hold modalDialog to close later */

var modalDialog;

 

/* used when creating a new contactListItem 

need to reference the Id field for setting the fieldLookupValue. */

var companyListItem;

 

var copyOfAddCompanyForm;

 

/* our startup method when the page loads */

_spBodyOnLoadFunctionNames.push("Initialize()");

 

3. Add the following JavaScript code within the Script block below the previous code.

 

 

Our Initialize() function retrieves the SharePoint ClientContext object and loads up the contacts list, company list and initializes contacts (Contacts list items).

/* Initialize useful variables and retrieve ClientContext */

function Initialize() {

 

    /* Retrieves the current ClientContext object */

    context = SP.ClientContext.get_current();

    web = context.get_web();

 

    // Get references to the lists we will use

    contactsList = web.get_lists().getByTitle(ContactsListName);

    companyList = web.get_lists().getByTitle(CompanyListName);

 

    // Get the list items for the contacts list 

    contacts = contactsList.getItems();

 

    // context.load tells the object model to load the objects scalar 

    // properties. Otherwise they will not be accessible 

 

    context.load(contacts);

    context.load(contactsList);

    context.executeQueryAsync(onListsLoaded);

}

 

4. Add the following JavaScript code within the Script block below the previous code.

 

 

The onListsLoaded() event is called asynchronously from the Initialize() function.

/* Event handler called loading the contacts and companies lists

This method dynamically renders an HTML table to display the list data */

function onListsLoaded() {

    var contactCount = contactsList.get_itemCount();

    var companyTable = document.getElementById("tblCompanyList");

    // clear out the table so when we add a new company there are not duplicates

    while (companyTable.rows.length > 0)

        companyTable.deleteRow(companyTable.rows.length – 1);

    var row = new Array();

    var content;

    var cell;

    var tbo = document.createElement(‘tbody’);

    // Loop for each contact

    for (contactIndex = 0; contactIndex < contactCount; contactIndex++) {

        // For each contact create a row in the table

        row[contactIndex] = document.createElement(‘tr’);

        // itemAt() retrieves the listitem

        var contactLI = contacts.itemAt(contactIndex);

        // get_item() retrieves the listitem value 

        // if the listitem value is from a lookup field we call get_lookupValue() 

        var companyName = 

        contactLI.get_item(ContactCompanyListField).get_lookupValue();

        var companyPhone = contactLI.get_item(CompanyPhoneField).get_lookupValue();

        var companyDesc = 

        contactLI.get_item(CompanyDescriptionField).get_lookupValue();

        var companyContact = contactLI.get_item(ContactFirstNameField) + " " + 

        contactLI.get_item(ContactLastNameField);

        var companyContactEmail = contactLI.get_item(ContactEmailField);

        // add the cells for the row

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyName);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyPhone);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyDesc);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyContact);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        cell = document.createElement(‘td’);

        content = document.createTextNode(companyContactEmail);

        cell.appendChild(content);

        row[contactIndex].appendChild(cell);

        // Add the row to the table body

        tbo.appendChild(row[contactIndex]);

    }

    // add the table body to the table

    companyTable.appendChild(tbo);

}

 

5. Add the following JavaScript code within the Script block below the previous code.

 

 

The ShowAddCompany() function finds the divAddCompanyElement (which we’ll add later) and displays it using the ModalDialog.showModalDialog() method.

/* Hide the modal dialog and display the updated UI */

function onContactAdded() {

    HideAddCompany();

}

 

/* Show a modalDialog with the contents of divAddCompany */

function ShowAddCompany() {

    var divAddCompany = document.getElementById("divAddCompany");

 

    // showModalDialog removes the element passed in from the DOM

    // so we save a copy and add it back later

    copyOfAddCompanyForm = divAddCompany.cloneNode(true);

 

    divAddCompany.style.display = "block";

    var options = { html: divAddCompany, width: 200, height: 350, dialogReturnValueCallback: ReAddClonedForm };

    modalDialog = SP.UI.ModalDialog.showModalDialog(options);

}

 

/* Close the modalDialog */

function HideAddCompany() {

    modalDialog.close();

    Initialize();

}

 

function ReAddClonedForm() {

    document.body.appendChild(copyOfAddCompanyForm);

}

 

6. Add the following JavaScript code within the Script block below the previous code.

 

 

The AddCompany() function creates a new list item in the  Company List.

/* Called from the Add Company modal dialog 

Creates a list item in the Company List list and when that query is executed

onCompanyAdded creates the contact list item. */

function AddCompany() {

    var lici1 = new SP.ListItemCreationInformation();

    companyListItem = companyList.addItem(lici1);

    companyListItem.set_item(CompanyNameField, getTBValue("txtCompanyName"));

    companyListItem.set_item(CompanyPhoneField, getTBValue("txtPhoneNumber"));

    companyListItem.set_item(CompanyDescriptionField, getTBValue("txtDescription"));

    companyListItem.update();

    context.load(companyListItem);

    // Execute the query to create the company list

    // onCompanyAdded is our call back method called when the call to the server has completed

    context.executeQuery(onCompanyAdded, OnError);

}

 

7. Add the following JavaScript code within the Script block below the previous code.

 

When the company list item is created we then create the lookup fields for the associated contacts. In the onContactAdded event handler the modal dialog is hidden.

/* Called when AddCompany has finished executing 

Note we have to wait until completion because we need access to companyListItem

to set the correct lookupId */

function onCompanyAdded(args) {

    var lici = new SP.ListItemCreationInformation();

    var companyLookupField = new SP.FieldLookupValue();

    companyLookupField.set_lookupId(companyListItem.get_id());

    var contactListItem = contactsList.addItem(lici);

    contactListItem.set_item(ContactTitleField, getTBValue("txtContactTitle"));

    contactListItem.set_item(ContactFirstNameField, getTBValue("txtFirstName"));

    contactListItem.set_item(ContactLastNameField, getTBValue("txtLastName"));

    contactListItem.set_item(ContactEmailField, getTBValue("txtEMail"));

    contactListItem.set_item(ContactCompanyListField, companyLookupField);

    contactListItem.update();

    context.executeQuery(onContactAdded);

}

/* Hide the modal dialog and display the updated UI */

function onContactAdded() {

    HideAddCompany();

}

 

8. Add the following JavaScript code within the Script block below the previous code.

 

Helper functions / Error handler

/* Error handler */

function OnError(sender, args) {

  var spnError = document.getElementById("spnError");

  spnError.innerHTML = args.get_message();

}

/* Helper function – shortcut to the value property of a textbox */

function getTBValue(elID) {

    var el = document.getElementById(elID);

    return el.value;

}

 

9. Add the following HTML code below the ending script block tag (</script>)

 

tblCompanyList is an empty table that our script dynamically adds rows/columns to for each contact/company. 

There is also a link to invoke ShowAddCompany() which will launch a modal dialog box.

<div style="font-weight: bold">Company List</div>

<br />

<table id="tblCompanyList" style="border: solid 1px silver">

    

</table>

<br />

<a href="javascript:ShowAddCompany()">Add a company</a>

<br /> 

 

 

<div id="divAddCompany" style="display: none; padding: 5px">

   <b>Company Information</b><br /><br />

 

    Name <br />

    <input type="text" id="txtCompanyName" /><br />

    Phone Number<br />

    <input type="text" id="txtPhoneNumber" /><br />

    Description<br />

    <input type="text" id="txtDescription" /><br />

    <b>Contact Information</b><br /><br />

    Title<br />

    <input type="text" id="txtContactTitle" /><br />

    First Name<br />

    <input type="text" id="txtFirstName" /><br />

    Last Name<br />

    <input type="text" id="txtLastName" /><br />

    E-Mail<br />

    <input type="text" id="txtEMail" /><br />

    <span id="spnError" style="color: Red" /><br />

    <input type="button" value="Add New Company" onclick="AddCompany()" />

</div>

The markup within divAddCompany will be displayed in a modal dialog that allows the user to input data to create a new company/contact. 

Task 3: Deploy and test the web part.

1. Right click on the ScriptOMExample project in the Solution Explorer and select Deploy. 

2. Add the web part to a web part page:

Click the Edit button to put the page in edit mode. 

Click Insert

Click Web Part

Click Custom

Click ScriptOMPart Title

Click Add 

 

image

 

The rendered web part looks like this:

 

image

3. To test the functionality of the web part click the Add a company link and fill out the modal form.

image

 

4. Click the Add New Company button and the new company will be added to the list dynamically with no post backs.

 

image

 

Exercise Summary

In this walkthrough you built a Visual Web Part that contains ECMAScript that uses the SharePoint Client Object Model and the SharePoint Dialog Platform to show a model dialog which gathers input for a new list item instance.

  

Advertisements
  1. Eric
    December 16, 2010 at 5:07 pm

    How do you get the value of a ‘Person or Group’ field?
    Tried .get_lookupValue()

    Do you know of a good book or site for learning ECMAscript as it pertains to SharePoint? Microsoft SDK not very helpful.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: