none
Creating a Lookup field programmatically using the Sharepoint Client OM RRS feed

  • Question

  • Hi 

    Any help on this would be most appreciated!

    I`m looking to add a Field of type=`Lookup` using the SharePoint Client Object Model

    So far I`ve been able to add fields of other types but cant find the right combination of shema attributes to get  [Fields].AddFieldAsXml() to work in adding the Lookup field. 

    Again any examples would be most appreciated

     

    Tuesday, April 24, 2012 5:53 PM

Answers

  • Here is an example that works using Managed CSOM. You must use a schema. So you will need to have the GUID of the lookup list.

    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();
    
      
    }


    Blog | SharePoint Field Notes Dev Tool | ClassMaster

    Wednesday, April 25, 2012 3:54 PM
  • Steve - That did it  - THANKYOU!!!

    Looks like it was the target list guid for the List attribute that did it (as opposed to the "Lists\ListinternalName" as is used in standard list def Xml)

    For anyone else looking for the solution - I'm posting my code which does a lookup of the existing list's guid and inserts it into the xml template:

    string fieldName = "myLookup8";
    string listName = "foolist";
    string targetListName = "HR2552-DepartReason";

    string lookupSchema = @"<Field Type='Lookup' DisplayName='{1}'
                            Required='FALSE' EnforceUniqueValues='FALSE'
                            List='{{{0}}}'
                            ShowField='Title' UnlimitedLengthInDocumentLibrary='FALSE'
                            RelationshipDeleteBehavior='None'
                            StaticName='{1}' Name='{1}'/>";

     

    ClientContext clientContext = new ClientContext("http://sharepoint/");

    List targetList = clientContext.Web.Lists.GetByTitle(targetListName);
    clientContext.Load(targetList, l => l.Id);
    clientContext.ExecuteQuery();
    string xml = String.Format(lookupSchema, targetList.Id, fieldName);

    List list = clientContext.Web.Lists.GetByTitle(listName);
    FieldCollection fields = list.Fields;

    Field lookupField = fields.AddFieldAsXml(xml, true, AddFieldOptions.AddToDefaultContentType);
    lookupField.Update();
    clientContext.ExecuteQuery();

    Wednesday, April 25, 2012 6:59 PM

All replies

  • Hi,

    Please take a look at this example Add lookup field with object model?


    Dmitry

    Lightning Tools LogoLightning Tools Check out our SharePoint tools and web parts | Lightning Tools Blog

    Wednesday, April 25, 2012 8:44 AM
  • Hi

    Take a look please to the following example

    How to Get\Set Lookup Field using ECMAScript SharePoint 2010

    Hope that help.

    Regards.


    Ahmed Naji SharePoint Geek
    MCP|MCTS
    My English SharePoint Blog | DotnetFinder My Arabic SharePoint Blog| CodeReloaded
    My Gallery Contributions
    SharePoint 2010 Twitter Web Part
    SharePoint 2010 Custom Timer Job

    Wednesday, April 25, 2012 9:18 AM
  • Hi,

    Look at this, this might help.

    using System; using Microsoft.SharePoint; namespace RelatedLists { class Program { staticvoid Main(string[] args) { using (SPSite siteCollection = new SPSite("http://localhost")) { using (SPWeb site = siteCollection.OpenWeb()) { SPList lookupList = site.Lists.TryGetList("Customers"); SPList relatedList = site.Lists.TryGetList("Pending Orders"); if (lookupList != null && relatedList != null) { string strPrimaryCol = relatedList.Fields.AddLookup("Customer ID", lookupList.ID, true); SPFieldLookup primaryCol = (SPFieldLookup)relatedList.Fields.GetFieldByInternalName(strPrimaryCol); primaryCol.LookupField = lookupList.Fields["ID"].InternalName; primaryCol.Indexed = true; primaryCol.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict; primaryCol.Update(); } } } Console.Write("\nPress ENTER to continue..."); Console.ReadLine(); } } }


    ARUN

    Wednesday, April 25, 2012 10:34 AM
  • DJARUN: Thanks but unfortunately I need to use the Sharepoint Client Object Model api (Microsoft.SharePoint.Client) due to security constraints imposed on the Server api



    • Edited by marcdroo Wednesday, April 25, 2012 2:21 PM
    Wednesday, April 25, 2012 1:10 PM
  • DavidH1986: Thanks but unfortunately this solution deals with adding the list / field declaratively via XML list definitions. I need to be able to add them in code


    • Edited by marcdroo Wednesday, April 25, 2012 2:22 PM
    Wednesday, April 25, 2012 1:39 PM
  • Dmitry Kaloshin:

    Ok this is the right path - the javascript code sample referenced contains the line

    var fieldName = list.AddLookup("Origin Country", targetList.ID, true);

    That's exactly what aI need to do... except in managed code  - here's my problem; that method does not seem to exist on Microsoft.Sharepoint.Client.List 
    or Microsoft.Sharepoint.Client.FieldCollection

    or put another way:

    ClientContext ctx = new ClientContext("http://sharepoint/");
    Web website = ctx.Web;
    ListCreationInformation ci = new ListCreationInformation();
    ci.Title = "MyList";
    ci.TemplateType = (int)ListTemplateType.GenericList;
    List lst = website.Lists.Add(ci);
    lst.AddLookup // <-  THIS METHOD DOES NOT EXIST 
    lst.Fields.AddLookup // <-  NOR DOES THIS

    Does anyone know what code the js method would map to ?



    • Edited by marcdroo Wednesday, April 25, 2012 2:24 PM
    Wednesday, April 25, 2012 1:57 PM
  • Here is an example that works using Managed CSOM. You must use a schema. So you will need to have the GUID of the lookup list.

    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();
    
      
    }


    Blog | SharePoint Field Notes Dev Tool | ClassMaster

    Wednesday, April 25, 2012 3:54 PM
  • Steve - That did it  - THANKYOU!!!

    Looks like it was the target list guid for the List attribute that did it (as opposed to the "Lists\ListinternalName" as is used in standard list def Xml)

    For anyone else looking for the solution - I'm posting my code which does a lookup of the existing list's guid and inserts it into the xml template:

    string fieldName = "myLookup8";
    string listName = "foolist";
    string targetListName = "HR2552-DepartReason";

    string lookupSchema = @"<Field Type='Lookup' DisplayName='{1}'
                            Required='FALSE' EnforceUniqueValues='FALSE'
                            List='{{{0}}}'
                            ShowField='Title' UnlimitedLengthInDocumentLibrary='FALSE'
                            RelationshipDeleteBehavior='None'
                            StaticName='{1}' Name='{1}'/>";

     

    ClientContext clientContext = new ClientContext("http://sharepoint/");

    List targetList = clientContext.Web.Lists.GetByTitle(targetListName);
    clientContext.Load(targetList, l => l.Id);
    clientContext.ExecuteQuery();
    string xml = String.Format(lookupSchema, targetList.Id, fieldName);

    List list = clientContext.Web.Lists.GetByTitle(listName);
    FieldCollection fields = list.Fields;

    Field lookupField = fields.AddFieldAsXml(xml, true, AddFieldOptions.AddToDefaultContentType);
    lookupField.Update();
    clientContext.ExecuteQuery();

    Wednesday, April 25, 2012 6:59 PM