Add a lookup field to a content type in sharepoint SharePoint Content Types, Site Columns or Columns
Thursday, December 13, 2018

Add a lookup field to a content type in sharepoint SharePoint Content Types, Site Columns or Columns


The Software Condition
Code is art!

Skip to content
  • Home
  • About

And on the Seventh Day, Monkeys Created SharePoint…
Some wacky HTML generation code I wrote the other week

Provisioning SharePoint Lookup Fields Programmatically

Posted on September 1, 2013 by N

There’s a large number of blog posts floating around on the topic of creating lookup fields (whether programmatically, via XML, or via the UI), as there are many ways of doing so with many variations, each with its own set of limitations. I’ve come up with a reasonably generic and flexible way of doing this with very few real drawbacks. It takes the form of the extension method below which I’ve modified slightly for public consumption.

public static SPFieldCollectionExt public static SPFieldLookup CreateLookupField(this SPFieldCollection fields, string title, string internalName, SPField lookupListTargetField, bool addToAllContentTypes, Action<SPFieldLookup> fieldActions) string caml = String.Format( "<Field Type=\"Lookup\" DisplayName=\"0\" Name=\"0\" List=\"1\" />", internalName, "" + lookupListTargetField.ParentList.ID.ToString().ToUpper() + ""); string nameOfCreatedField = fields.AddFieldAsXml(caml, true, addToAllContentTypes ? SPAddFieldOptions.AddToAllContentTypes : SPAddFieldOptions.AddToDefaultContentType); return fields.UpdateField<SPFieldLookup>(nameOfCreatedField, f => f.Title = title; f.LookupWebId = lookupListTargetField.ParentList.ParentWeb.ID; f.LookupField = lookupListTargetField.InternalName; if (fieldActions != null) fieldActions(f); ); static T UpdateField<T>(this SPFieldCollection fields, string fieldInternalName, Action<T> fieldActions) where T : SPField var field = (T)fields.GetFieldByInternalName(fieldInternalName); fieldActions(field); field.Update(); return (T)fields.GetFieldByInternalName(fieldInternalName); 

Which can be called using code like this:

site.RootWeb.Lists["Pages"].Fields.CreateLookupField("My Lookup Field", "MyLookupField", lookupTargetField, true, f => f.AllowMultipleValues = true; f.Required = true;
);

Advantages:

  • This method allows a lookup field to target a list outside the current web. Most methods (particularly CAML oriented ones) don’t as they rely on setting List to a web relative URL rather than a list ID.
  • This method allows any number of field properties to be configured in a strongly typed fashion by way of a lambda (see the final advantage below). And Update() is called automatically afterwards.
  • This method uses  AddFieldAsXml()  instead of  Add()  or  AddLookup() . This means:
    • You can add a list field to all content types available in that list. Basically, without extra work, the latter two methods cannot be used to achieve what you’d accomplish in the UI by ticking the below box:
      pic
    • It can be used to add custom field types -though this would only matter if you were subclassing SPFieldLookup. More generally speaking, a CreateField() wrapper (one which can create any type of field) should call the first method for this reason.
  • This abstracts away lookup/CAML nastiness. E.g. it’s not sufficient to supply the list ID – despite its uniqueness, one must still provide the LookupWebId. But callers of this method need not worry about such SP idiosyncrasies.
  • It uses a programmatic approach – some will disagree here, but one day I’ll write a blog post which explains why I consider this approach superior. Of course, this is a disadvantage if in your codebase, you do everything via XML.

Disadvantages:

  • The lookup target list must exist prior to calling this. But this is most likely a non-issue – if you’re adding a lookup field programmatically, you’re probably also provisioning the list programmatically… therefore, you have control over when this happens.
  • This method will only add a lookup to existing content types. Content types added after the fact will need to be updated.

This entry was posted in C# , SharePoint and tagged addfield , addfieldasxml , addlookup , caml , lookup , object model , programmatically , provision , sharepoint , spfieldcollection , spfieldlookup . Bookmark the permalink .

And on the Seventh Day, Monkeys Created SharePoint…
Some wacky HTML generation code I wrote the other week

Leave a Reply Cancel reply

  • Recent Posts

    • Alternative to Solution Items/Folders
    • TDD and the Silver Bullet Express
    • NuGet issues with Nested Solutions / Branches
    • Some wacky HTML generation code I wrote the other week
    • Provisioning SharePoint Lookup Fields Programmatically
  • Recent Posts

    • Alternative to Solution Items/Folders
    • TDD and the Silver Bullet Express
    • NuGet issues with Nested Solutions / Branches
    • Some wacky HTML generation code I wrote the other week
    • Provisioning SharePoint Lookup Fields Programmatically
  • Recent Comments

    • Sam S on TFS Pending Changes – Ignoring Files which are Identical to the Originals
    • earnest on TFS Pending Changes – Ignoring Files which are Identical to the Originals
    • Erich Mühsam on TFS Pending Changes – Ignoring Files which are Identical to the Originals
    • Evan Roberts on TFS Pending Changes – Ignoring Files which are Identical to the Originals
    • tadele on C/C++ Assertions and Defining Your Own Assert Macro
  • Categories

    ASP .NET
    C
    C#
    C++
    Functional Programming
    General
    JavaScript
    Rants
    SharePoint
    Tools
    User Interfaces
    Version Control
    Web
  • Archives

    • November 2014
    • September 2014
    • June 2014
    • September 2013
    • August 2013
    • June 2013
    • April 2012
    • March 2012
    • February 2012
    • September 2011
    • July 2011
    • May 2011
    • April 2011
    • March 2011
    • November 2010
    • October 2010
    • September 2010
    • August 2010
    • July 2010

The Software Condition

Proudly powered by WordPress.

Stack Overflow



  1. Log In
    Sign Up

  2. current community


    • Stack Overflow

      help
      chat

    • Meta Stack Overflow

    your communities

    Sign up or log in to customize your list.

    more stack exchange communities

    company blog

    • Tour

      Start here for a quick overview of the site

    • Help Center

      Detailed answers to any questions you might have

    • Meta

      Discuss the workings and policies of this site

    • About Us

      Learn more about Stack Overflow the company

    • Business

      Learn more about hiring developers or posting ads with us

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service .

Add a lookup field to a content type in sharepoint

Ask Question


up vote
6
down vote

favorite

5

How can I add a lookup field to a content type in sharepoint using the xml definition? (I’m getting errors).

Things to note:
– The lookup list will exist when the content type is added to the document library.
– The lookup list will always have the same name.
– The lookup list has a space in the name.

This is what I’ve added to the xml:

 <Field ID="GUID" Type="Lookup" List="$Resources:core,lists_Folder;/List%20Name" ShowField="Title" Name="MyLookupFieldName" DisplayName="MyLookupFieldName" StaticName="MyLookupFieldName" Hidden="FALSE" Required="FALSE" Sealed="TRUE" >

When I then programatically add the content type to a document library I get an exception (with no useful information), and the following is logged to the sharepoint log:

08/18/2009 17:13:39.50 w3wp.exe (0x08B8) 0x11B0 Windows SharePoint Services Database 6f8g Unexpected Unexpected query execution failure, error code 8114. Additional error information from SQL Server is included below. “Error converting data type nvarchar to uniqueidentifier.” Query text (if available): “?=call proc_GetListMetaDataAndEventReceivers(?,?,?,?,?,?)”

sharepoint content-type lookup-field

share | improve this question

edited Aug 18 ’09 at 17:26

dahlbyk

52k887111

asked Aug 18 ’09 at 16:35

zikoziko

1852719

  • What does the XML look like? It looks like it got stripped out when you posted it
    –  Yuliy
    Aug 18 ’09 at 16:40

  • … <FieldRef ID="GUID" Name="MyLookupFieldName"/> … <Field ID="GUID" Type="Lookup" List="Lists/List%20Name" ShowField="Title" Name="MyLookupFieldName" DisplayName="MyLookupFieldName" StaticName="MyLookupFieldName" Hidden="FALSE" Required="FALSE" Sealed="TRUE" > … What else do you want to see?
    –  zikoziko
    Aug 19 ’09 at 10:08

add a comment  | 

3 Answers
3

active

oldest

votes


up vote
9
down vote

Luckily, in SharePoint 2010, you can declaratively do this by setting all required properities as shown in the following working example.

<Field Type="Lookup" DisplayName="Link Type" Description="Represents link type."
Required="TRUE" EnforceUniqueValues="FALSE" List="Lists/Links Types" WebId="~sitecollection"
Overwrite="TRUE" PrependId="TRUE" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE"
Group="Research Links Columns" ID="a15e9fa2-4ea0-41f1-a583-b21d53cf72d3"
SourceID="30650f6f-fbb8-4acc-a935-29745f5d3c59" StaticName="Link_x0020_Type"
Name="Link_x0020_Type" Hidden="FALSE" ReadOnly="FALSE"></Field>

It’s important to set WebId to have value of “~sitecollection” and set Overwrite to be TRUE.
More info

share | improve this answer

answered Jun 27 ’11 at 15:45

Ahmed

8,7482385128

  • Awesome, I tried everything else– this worked for me. Thank you!
    –  Kevin Dostalek
    Aug 2 ’11 at 23:58

  • Instead of using WebId="~sitecollection" you can also directly refer to the name of a subsite containing the list you want to link your lookup field with.
    –  Koen Zomers
    May 23 ’12 at 10:40

  • can lookup field be set to refer the same list it is part of?
    –  Pranavan Maru
    Jun 6 ’14 at 12:42

add a comment  | 


up vote
2
down vote

The problem is that you need to reference the GUID of the list not its title. As you probably won’t know the GUID of the list then you can’t do this without executing some custom code afterwards.

Even if you aren’t using VSeWSS, the last steps in the post dahlbyk has linked to show you how to do this. Chris O’Brien has gone to the trouble of making a CodePlex project that will help you if you aren’t using VSeWSS.

share | improve this answer

answered Aug 18 ’09 at 18:36

Alex Angas

33.6k37122197

  • There’s no requirement to add a reference to the list GUID. Adding a reference to the List title as shown in Ahmed his XML sample is perfectly valid as well and solves the "I don’t know the GUID at forehand" problem.
    –  Koen Zomers
    May 22 ’12 at 15:55

add a comment  | 


up vote
1
down vote

Ok, so I couldn’t get the xml definition of a field for a content type to work for me for some reason. I did find out how to do it in code. The solution that worked for me is to not add the Field definition in xml, instead add it in code:

  • Add the content type to the list (in site definition code, or wherever).
  • Add a field lookup to the given SPWeb (so the field is a web? field, rather than a site field)
  • Add a new field link to the list content type.
  • Update the content type.

For example:

SPContentType myContentType = myWeb.Site.RootWeb.ContentTypes["MyContentType "];
myLib.ContentTypes.Add(myContentType);
myContentType = myLib.ContentTypes["MyContentType "];
myWeb.Fields.AddLookup("MyLookupFieldName", myWeb.Lists["MyLookupListName"].ID, false);
SPFieldLink myFIeldLink = new SPFieldLink(myWeb.Fields["MyLookupFieldName"]);
myContentType.FieldLinks.Add(myFIeldLink);
myContentType.Update();

share | improve this answer

edited Feb 22 ’12 at 12:02

Stu Pegg

9791237

answered Aug 19 ’09 at 14:25

zikoziko

1852719

add a comment  | 

Not the answer you’re looking for? Browse other questions tagged sharepoint content-type lookup-field or ask your own question .

asked

9 years, 3 months ago

viewed

27,969 times

active

6 years, 9 months ago

Visit Chat

Linked

1

Sharepoint Content type with lookup field

Related

1144

Proper MIME media type for PDF files

9402

What is the correct JSON content type?

4

How to create a lookup column that targets a Doc Lib and uses the ‘Name’ of the document?

0

What are the killer uses of Content Types for Lists (not Document Libraries)?

3

Get username from SharePoint User field in List

0

Content type with workflow and lookup column

1

Limit on number of items in lookup column dropdown list when attaching content types to document libraries

0

How to look up the document library in its local sub site where used, rather than in the root site?

0

SharePoint JSOM: get SPFolder custom field value

1

Sharepoint 2010 Content types Hyperlinks and Word QuickParts

Hot Network Questions

  • Close all tabs in Safari except for one

  • 9sums – a logical deduction puzzle

  • What to do if you notice a substantial improvement to a result in a paper whilst refereeing it?

  • Our product is ruining users privacy, without telling them

  • How powerful would an always-on Truesight ability be for a PC?

  • My cat is not eating anything after the death of the fellow cat

  • What should I choose, Life or Nirvana?

  • Create styled image programmatically

  • Trifid Cipher (without keyword)

  • Fill the Bucket

  • Does a client certificate identify the owner to unrelated websites?

  • Units in group rings.

  • What would be the necessary conditions to rain bubbles?

  • How do microstrips actually represent lumped components?

  • Word for a person who uploaded a file?

  • Working Iterative formula for a system of equations

  • Is it possible that the return ticket of a round-trip is counterfeit?

  • How much water should I let my dog drink?

  • Could/Should I cite a paper that I am refereeing?

  • "Too expensive for me to afford it" why ungrammatical?

  • What are these "pimples" on the jet engine for?

  • Are there mistakes on the pre-rolled Basic Set wizard and ranger character sheets?

  • How dangerous is a 500-year-old nuclear warhead?

  • Do industry professionals building games using UE4 use Blueprints at all, or do they use C++ exclusively?

more hot questions


question feed

default

Stack Overflow works best with JavaScript enabled

Stack Overflow



  1. Log In
    Sign Up

  2. current community


    • Stack Overflow

      help
      chat

    • Meta Stack Overflow

    your communities

    Sign up or log in to customize your list.

    more stack exchange communities

    company blog

    • Tour

      Start here for a quick overview of the site

    • Help Center

      Detailed answers to any questions you might have

    • Meta

      Discuss the workings and policies of this site

    • About Us

      Learn more about Stack Overflow the company

    • Business

      Learn more about hiring developers or posting ads with us

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service .

Add a lookup field to a content type in sharepoint

Ask Question


up vote
6
down vote

favorite

5

How can I add a lookup field to a content type in sharepoint using the xml definition? (I’m getting errors).

Things to note:
– The lookup list will exist when the content type is added to the document library.
– The lookup list will always have the same name.
– The lookup list has a space in the name.

This is what I’ve added to the xml:

 <Field ID="GUID" Type="Lookup" List="$Resources:core,lists_Folder;/List%20Name" ShowField="Title" Name="MyLookupFieldName" DisplayName="MyLookupFieldName" StaticName="MyLookupFieldName" Hidden="FALSE" Required="FALSE" Sealed="TRUE" >

When I then programatically add the content type to a document library I get an exception (with no useful information), and the following is logged to the sharepoint log:

08/18/2009 17:13:39.50 w3wp.exe (0x08B8) 0x11B0 Windows SharePoint Services Database 6f8g Unexpected Unexpected query execution failure, error code 8114. Additional error information from SQL Server is included below. “Error converting data type nvarchar to uniqueidentifier.” Query text (if available): “?=call proc_GetListMetaDataAndEventReceivers(?,?,?,?,?,?)”

sharepoint content-type lookup-field

share | improve this question

edited Aug 18 ’09 at 17:26

dahlbyk

52k887111

asked Aug 18 ’09 at 16:35

zikoziko

1852719

  • What does the XML look like? It looks like it got stripped out when you posted it
    –  Yuliy
    Aug 18 ’09 at 16:40

  • … <FieldRef ID="GUID" Name="MyLookupFieldName"/> … <Field ID="GUID" Type="Lookup" List="Lists/List%20Name" ShowField="Title" Name="MyLookupFieldName" DisplayName="MyLookupFieldName" StaticName="MyLookupFieldName" Hidden="FALSE" Required="FALSE" Sealed="TRUE" > … What else do you want to see?
    –  zikoziko
    Aug 19 ’09 at 10:08

add a comment  | 

3 Answers
3

active

oldest

votes


up vote
9
down vote

Luckily, in SharePoint 2010, you can declaratively do this by setting all required properities as shown in the following working example.

<Field Type="Lookup" DisplayName="Link Type" Description="Represents link type."
Required="TRUE" EnforceUniqueValues="FALSE" List="Lists/Links Types" WebId="~sitecollection"
Overwrite="TRUE" PrependId="TRUE" ShowField="Title" UnlimitedLengthInDocumentLibrary="FALSE"
Group="Research Links Columns" ID="a15e9fa2-4ea0-41f1-a583-b21d53cf72d3"
SourceID="30650f6f-fbb8-4acc-a935-29745f5d3c59" StaticName="Link_x0020_Type"
Name="Link_x0020_Type" Hidden="FALSE" ReadOnly="FALSE"></Field>

It’s important to set WebId to have value of “~sitecollection” and set Overwrite to be TRUE.
More info

share | improve this answer

answered Jun 27 ’11 at 15:45

Ahmed

8,7482385128

  • Awesome, I tried everything else– this worked for me. Thank you!
    –  Kevin Dostalek
    Aug 2 ’11 at 23:58

  • Instead of using WebId="~sitecollection" you can also directly refer to the name of a subsite containing the list you want to link your lookup field with.
    –  Koen Zomers
    May 23 ’12 at 10:40

  • can lookup field be set to refer the same list it is part of?
    –  Pranavan Maru
    Jun 6 ’14 at 12:42

add a comment  | 


up vote
2
down vote

The problem is that you need to reference the GUID of the list not its title. As you probably won’t know the GUID of the list then you can’t do this without executing some custom code afterwards.

Even if you aren’t using VSeWSS, the last steps in the post dahlbyk has linked to show you how to do this. Chris O’Brien has gone to the trouble of making a CodePlex project that will help you if you aren’t using VSeWSS.

share | improve this answer

answered Aug 18 ’09 at 18:36

Alex Angas

33.6k37122197

  • There’s no requirement to add a reference to the list GUID. Adding a reference to the List title as shown in Ahmed his XML sample is perfectly valid as well and solves the "I don’t know the GUID at forehand" problem.
    –  Koen Zomers
    May 22 ’12 at 15:55

add a comment  | 


up vote
1
down vote

Ok, so I couldn’t get the xml definition of a field for a content type to work for me for some reason. I did find out how to do it in code. The solution that worked for me is to not add the Field definition in xml, instead add it in code:

  • Add the content type to the list (in site definition code, or wherever).
  • Add a field lookup to the given SPWeb (so the field is a web? field, rather than a site field)
  • Add a new field link to the list content type.
  • Update the content type.

For example:

SPContentType myContentType = myWeb.Site.RootWeb.ContentTypes["MyContentType "];
myLib.ContentTypes.Add(myContentType);
myContentType = myLib.ContentTypes["MyContentType "];
myWeb.Fields.AddLookup("MyLookupFieldName", myWeb.Lists["MyLookupListName"].ID, false);
SPFieldLink myFIeldLink = new SPFieldLink(myWeb.Fields["MyLookupFieldName"]);
myContentType.FieldLinks.Add(myFIeldLink);
myContentType.Update();

share | improve this answer

edited Feb 22 ’12 at 12:02

Stu Pegg

9791237

answered Aug 19 ’09 at 14:25

zikoziko

1852719

add a comment  | 

Not the answer you’re looking for? Browse other questions tagged sharepoint content-type lookup-field or ask your own question .

asked

9 years, 3 months ago

viewed

27,969 times

active

6 years, 9 months ago

Visit Chat

Linked

1

Sharepoint Content type with lookup field

Related

1144

Proper MIME media type for PDF files

9402

What is the correct JSON content type?

4

How to create a lookup column that targets a Doc Lib and uses the ‘Name’ of the document?

0

What are the killer uses of Content Types for Lists (not Document Libraries)?

3

Get username from SharePoint User field in List

0

Content type with workflow and lookup column

1

Limit on number of items in lookup column dropdown list when attaching content types to document libraries

0

How to look up the document library in its local sub site where used, rather than in the root site?

0

SharePoint JSOM: get SPFolder custom field value

1

Sharepoint 2010 Content types Hyperlinks and Word QuickParts

Hot Network Questions

  • Trifid Cipher (without keyword)

  • How to graph a logistic equation using tikz

  • Does a client certificate identify the owner to unrelated websites?

  • How to handle being asked to automate jobs as a temp worker

  • What if a law is literally impossible to follow?

  • What is the utilitarian purpose of artificial waterfalls?

  • How to poweroff when there’s no systemd/init (e.g. using init=/bin/bash)?

  • Garlic press with minimum force required

  • Word for a person who uploaded a file?

  • How dangerous is a 500-year-old nuclear warhead?

  • MOSFET W/L ratio limits: what’s (un)reasonable?

  • Can this Wish effect be dispelled?

  • Why was Frodo unable to destroy the Ring?

  • Create styled image programmatically

  • Units in group rings.

  • Leaflet variable for import data geojson

  • Is it acceptable to publish student names with the label ‘stupid question’, on a publicly-visible website?

  • Using private software at work

  • How do I produce a "New" record button to look like a standard "New" button?

  • A function to fill in a column with NA of the same type

  • Why are fuel tanks located in wings?

  • How to disable the "website is now full screen" warning in Firefox?

  • O(·) is not a function, so how can a function be equal to it?

  • Please help identify this physics apparatus!

more hot questions


question feed

default

Stack Overflow works best with JavaScript enabled