In this post I show how to create a lookup column in SharePoint 2013 using JavaScript and CSOM.
I used this code within a SharePoint App that has beed deployed to Office 365. The code should also work in SharePoint 2013 On-Premis Apps. The lists are created in host web.
Step 1: Context objects and global variables
We need access to the SP.Context object and SP.Web object. If you develop an app and needs access to the host web, read this arcticle from mavention: SharePoint App accessing data from host web.
// Assign your App-Context and Web-Object to these variables
var m_appContext = {...};
var m_hostWeb = {...};
// The following variables are used later in this code across multiple functions.
var m_createListLookup = undefined;
var m_createListLookupMain = undefined;
var m_createFieldLookup = undefined;
Step 1: Create two lists
First we need two lists where one list is the lookup list for the other.
// Lookup list
var listCreationInfoLookup = new SP.ListCreationInformation();
listCreationInfoLookup.set_title('Lookup List');
listCreationInfoLookup.set_templateType(SP.ListTemplateType.genericList);
m_createListLookup = m_hostWeb.get_lists().add(listCreationInfoLookup);
m_appContext.load(m_createListLookup);
// List that will have lookup field
var listCreationInfoLookupMain = new SP.ListCreationInformation();
listCreationInfoLookupMain.set_title('Lookuping List');
listCreationInfoLookupMain.set_templateType(SP.ListTemplateType.genericList);
m_createListLookupMain = m_hostWeb.get_lists().add(listCreationInfoLookupMain);
m_appContext.load(m_createListLookupMain);
// When lists are created, we continue to create the field in the method create_ListsWithLookupField_Succeeded
m_appContext.executeQueryAsync(
create_ListWithLookupField_Succeeded,
function () {});
Step 2: Create Lookup field
Now we can add a lookup field to the List “Lookuping List” that looks for the title field from the List “Lookup List”.
create_ListWithLookupField_Succeeded = function (sender, args) {
// Add Lookup Field
m_createFieldLookup = m_createListLookupMain.get_fields().addFieldAsXml(
'<Field DisplayName=\'MyField\' Type=\'Lookup\' />',
true,
SP.AddFieldOptions.defaultValue
);
var fieldLookup = m_appContext.castTo(m_createFieldLookup, SP.FieldLookup);
// Here is the magic:
fieldLookup.set_lookupList(m_createListLookup.get_id());
fieldLookup.set_lookupField("Title");
fieldLookup.update();
m_appContext.load(m_createFieldLookup);
m_appContext.executeQueryAsync(
create_ListWithLookupField_Succeeded2,
function () { });
},
create_ListWithLookupField_Succeeded2 = function (sender, args) {
alert("Field created: " + m_createFieldLookup.get_title());
},
Now you can browser your host web and add data to the lists and see that there is a lookup field looking up data from the other list.

December 31, 2012 

One Response to “Create SP.FieldLookup using JavaScript and CSOM”