Sharepoint - How to create lookup columns in SharePoint Lists within SharePoint Apps?

How to provision Fields using JavaScript (CSOM) in SharePoint 2010/2013

1 Provision List column

function ProvisionFieldInList(fieldSchema, listTitle)
      {
            var context = SP.ClientContext.get_current();
            var list = context.get_web().get_lists().getByTitle(listTitle);
            var fields = list.get_fields();
            var fieldToAdd = fields.addFieldAsXml(fieldSchema, true, SP.AddFieldOptions.AddToDefaultContentType);
            fieldToAdd.update();
            context.load(list);
            context.load(fields);
            context.load(fieldToAdd);
            context.executeQueryAsync(
                  function(){
                     //Provisioned successfully                
                  }, 
                  function(sender, args){
                     //Error handling goes here...
                  });
      }

2 Provision site column

function ProvisionField(fieldSchema)
  {
        var context = SP.ClientContext.get_current();
        var fields = context.get_web().get_fields();
        var fieldToAdd = fields.addFieldAsXml(fieldSchema, true, SP.AddFieldOptions.AddToDefaultContentType);
        fieldToAdd.update();
        context.load(fields);
        context.load(fieldToAdd);
        context.executeQueryAsync(
              function(sender, args){
                 //Provisioned successfully                
              }, 
              function(sender, args){
                 //Error handling goes here...
              });
  }

Examples:

The example below demonstrate how to create Lookup fields

function CreateLookupFields()
{

      var lookupFieldSchema = ["<Field Type='Lookup' DisplayName='OfficeType'",
                                    "Required='FALSE'",  
                                    "List='{E0D2646A-63BE-4010-ABC7-4A5E2B8EF0E7}'",
                                    "ShowField='Title'", 
                                    "StaticName='OfficeType'",
                                    "Name='OfficeType'/>"].join(' ');

      //Create Lookup field for List 
      ProvisionFieldInList(lookupFieldSchema,'Nokia Offices');


      var lookupFieldSchema2 = ["<Field Type='Lookup' DisplayName='OfficeType2'",
                                    "Required='FALSE'",  
                                    "List='{E0D2646A-63BE-4010-ABC7-4A5E2B8EF0E7}'",
                                    "ShowField='Title'", 
                                    "StaticName='OfficeType2'",
                                    "Name='OfficeType2'/>"].join(' ');

      //Create Lookup field in web
      ProvisionField(lookupFieldSchema2);                              

}      

SP.SOD.executeOrDelayUntilScriptLoaded(CreateLookupField, 'sp.js');

In order to add a lookup field to a list, you need to create field xml and add it to the fields collection of the list using fields.addFieldAsXml. The code below shows it in Managed CSOM

public static void AddLookupField()
{
            string lookupSchema = @"<Field Type='Lookup' DisplayName='mylookup2' 
                                    Required='FALSE' EnforceUniqueValues='FALSE'
                                    List='{70d6098c-6ba0-4e9e-b101-a60b88fc226a}' 
                                    ShowField='Title' UnlimitedLengthInDocumentLibrary='FALSE' 
                                    RelationshipDeleteBehavior='None' 
                                    StaticName='mylookup' Name='mylookup2'/>";

            ClientContext clientContext = new ClientContext("http://basesmc2008");
            List list = clientContext.Web.Lists.GetByTitle("tester");
            FieldCollection fields = list.Fields;

            clientContext.Load(list);
            clientContext.Load(fields);

            clientContext.ExecuteQuery();

            Field lookupField = fields.AddFieldAsXml(lookupSchema, true, AddFieldOptions.AddToDefaultContentType);
            lookupField.Update();

            clientContext.Load(lookupField);
            clientContext.ExecuteQuery();


}

Since you are using SharePoint Hosted app, you will need to change it to Javacript client object model: SOURCE


You need to remember for SharePoint hosted apps:

Scenario 1: If you are creating look-up column in host web then you need to set the right App permissions in AppManifest.xml.

Scenario 2: If you require look-up column in App web then you can simply re-provision look-up column in List 2 using Visual Studio.

Afore-mentioned scenarios can also be achieve programmatically (as suggested by Vadim) using CSOM javascript/XML.

Tags: