When creating a field, whether you are using CAML, server-side object mode, or one of the client-side object models, you typically specify the following attributes:

  • The ID of the fied, which is a GUID
  • The Name, which is the internal name of the field
  • The StaticName, which is the static name of the field
  • The DisplayName, which is display name of the field
  • The Type attribute which indicates the data type of the field

Only the attributes ID, Name and Type are required. You also have a number of other attributes that you set in order to indicate whether the field is required, whether the field can be used in a sort order, etc. You can find a detailed list of possible attributes and a detailed description in this MSDN reference article.

The order in which you specify the attributes is of no importance, but I always have the habit of specifying the ID first, then the internal name, display name and data type (except in this post where the focus lays on the different data types that can be used  ). Setting the internal name is required, while the defining the static name is optional. The difference between the two fields is that the internal name needs to be unique within the site collection, and SharePoint can change this name at creation time to guarantee uniqueness. Static name must not be unique and will therefore not be changed by SharePoint.  Therefore it can be practical to specify both Name and StaticName attributes and set them to the same value.

Another point of interest is the SourceID attribute. You can set it, but you don't have to. Out of the box SharePoint fields all have the SourceID set to http://schemas.microsoft.com/sharepoint/v3,  and a lot of developers have the habit set their own custom fields to this same value. But you don't have to do this. If you look more closely at a field manually created by a user directly on a list, the sourceID is set to {$ListId:Lists/Demo List;}. A good practice is for example to build your SourceID as follows:

http://schemas.<company&gt;.com/<name of the application>/<release>

for example:

http://schemas.biwug.be/camldesigner/v1

This post gives you an overview of the different field types that you can create through CSOM.

Create a Text field

A simple text field can be created as follows:

string schemaTextField = "<Field ID='<GUID>' Type='Text' Name='LastName' StaticName='LastName' DisplayName='Last Name' />";

Field simpleTextField = demoList.Fields.AddFieldAsXml(schemaTextField, true, AddFieldOptions.AddToDefaultContentType);

clientContext.ExecuteQuery();

Written like this, SharePoint will ignore the internal name you specified, and will apply the display name. To make sure your internal name is applied, you have to add the AddFieldOptions.AddFieldInternalNameHint:

string schemaTextField = "<Field Type='Text' Name='LastName' StaticName='LastName' DisplayName='Last Name' />";

Field simpleTextField = demoList.Fields.AddFieldAsXml(schemaTextField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

You can find the (only) explanation of the AddFieldOptions enumeration here.

Know that this enumeration has the FlagsAttribute to allow a bitwise combination, meaning that you can combine the different values:

Field simpleTextField = demoList.Fields.AddFieldAsXml(schemaTextField, true, AddFieldOptions.AddFieldInternalNameHint | AddFieldOptions.AddToAllContentTypes);

Creating a hidden field

If you want to create a hidden field, you have to include the hidden attribute and set it to true:

string schemaTextField = "<Field Type='Text' Name='LastName' StaticName='LastName' DisplayName='Last Name' Hidden='TRUE' />";

Field simpleTextField = demoList.Fields.AddFieldAsXml(schemaTextField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Omitting this attribute will create a field visible to your users.

You can also

Creating an indexed field

While creating a field, you can also index it.

Field f = list.Fields.GetByInternalNameOrTitle(fieldName);

clientContext.Load(f);

clientContext.ExecuteQuery();

f.Indexed = true;

f.Update();

clientContext.ExecuteQuery();

Create a multi line field

You can create different types of multi line fields:

  • a plain text field
  • a rich text field
  • an enhanced text field

A plain multi line text field

string schemaMultilineTextField = "<Field ID='<GUID>' Type='Note' Name='Comments' StaticName='Comments'

DisplayName='Comments' NumLines='6' RichText='FALSE' Sortable='FALSE' />"

Field multilineTextField = demoList.Fields.AddFieldAsXml(schemaMultilineTextField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

A rich multi line text field

string schemaRichTextField = "<Field ID='<GUID>' Type='Note' Name='Comments' StaticName='Comments'

DisplayName='Comments' NumLines='6' RichText='TRUE' Sortable='FALSE' />"

Field multilineTextField = demoList.Fields.AddFieldAsXml(schemaRichTextField , true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

An enhanced multi line text field

string schemaRichTextField = "<Field ID='<GUID>' Type='Note' Name='Comments' StaticName='Comments'

DisplayName='Comments' NumLines='6' RichText='TRUE' RichTextMode='FullHtml' IsolateStyles='TRUE' Sortable='FALSE' />"

Field multilineTextField = demoList.Fields.AddFieldAsXml(schemaRichTextField , true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Create a boolean field

In the SharePoint user interface this is called a Yes/No field.

string schemaBooleanField = "<Field Type='Text' Name='Married' StaticName='Married' DisplayName='Married' />";

Field booleanField = demoList.Fields.AddFieldAsXml(schemaBooleanField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

If you want to set a default value, you have to specify a 0 for false or a 1 for true:

string schemaBooleanField = "<Field Type='Boolean' Name='Married' StaticName='Married' DisplayName='Married'>"

+ "<Default>0</Default></Field>;

Field booleanField = demoList.Fields.AddFieldAsXml(schemaBooleanField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Create a DateTime field

A DateTime field is created in a similar way, but you can set additional properties, like the Format property. In case of a DateTime field, the format attribute will indicate whether you want to create a date only field, or a date time field.

Date only field

string schemaBirthDate = "<Field ID='<GUID>' Type='DateTime' Name='BirthDate' StaticName='BirthDate'

DisplayName='Birth date' Format='DateOnly' >"

+ "<Default>[Today]</Default></Field>";

Field birthDateField = demoList.Fields.AddFieldAsXml(schemaBirthDate, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

The Default node is optional. The sample code snippet indicates that today's date will be suggested to the user. If nothing is specified, no date will be sugested to the user.

Date and time field

string schemaArrivalField = "<Field ID='<GUID>' Type='DateTime' Name='ArrivalDateTime' StaticName='ArrivalDateTime'

DisplayName='Arrival' Format='DateTime'>"

   + "<Default>[Now]</Default></Field>";

Field birthDateField = demoList.Fields.AddFieldAsXml(schemaBirthDate, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

As in previous code sample, the Default node is optional. This sample code snippet indicates that the current date and time will be suggested to the user. If nothing is specified.

Create a Number field

With this type of field, you have to specify the different choices on beforehand. You can also choose if you want to show the different options within a dropdown list or with radio buttons.

string schemaNumberField = "<Field ID='<GUID>' Type='Number' Name='NbrOfEmployees' StaticName='NbrOfEmployees'

DisplayName='Number of employees' />";

Field birthDateField = demoList.Fields.AddFieldAsXml(schemaBirthDate, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Previous code snippet will create a standard number field where the user can set positive and negative numbers, and where the number of decimals is generated automatically. If you want to declare a number field that only allows positive numbers, you will have to declare it this way:

string schemaPosNumberField = "<Field ID='<GUID>' Type='Number' Name='NbrOfEmployees' StaticName='NbrOfEmployees'

DisplayName='Number of employees' Min='0' />";

And if you want to restrict the range of values that can be entered by the user, you have to declare the number field the following way:

string schemaNumberField = "<Field ID='<GUID>' Type='Number' Name='NbrOfEmployees' StaticName='NbrOfEmployees'

DisplayName='Number of employees' Min='0' Max='5000'/>";

You can also define the number of decimals:

string schemaNumberField = "<Field ID='<GUID>' Type='Number' Name='NbrOfEmployees' StaticName='NbrOfEmployees'

   DisplayName='Number of employees' Min='0' Decimals='0' />";

You can also create a percentage field by using the Number type. In that case you have to add an addition attribute Percentage, which you have to set to true:

string schemaPercentageField = "<Field ID='<GUID>' Type='Number' Name='NbrOfEmployees' StaticName='NbrOfEmployees'

   DisplayName='Number of employees' Percentage='True' Decimals='2' />";

Create a Choice field

With this type of field, you have to specify the different choices on beforehand. You can also choose if you want to show the different options within a dropdown list or with radio buttons.

Dropdown list

string schemaChoiceField = "<Field ID='<GUID>' Type='Choice' DisplayName='Menu Choice' Name='MenuChoice' StaticName='MenuChoice'

Format='Dropdown'>"

+ "<Default>Meat menu</Default>"

   +         "<CHOICES>"

   +         "    <CHOICE>Fish menu</CHOICE>"

   +         "    <CHOICE>Vegeterian menu</CHOICE>"

   +         "</CHOICES>"

+ "</Field>";

Field choiceField = demoList.Fields.AddFieldAsXml(schemaChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Radio buttons

string schemaChoiceField = "<Field ID='<GUID>' Type='Choice' Name='DessertChoice' StaticName='DessertChoice'

DisplayName='Desserts' Format='RadioButtons'>"

   + "<Default>Ice cream</Default>"

   +         "<CHOICES>"

   +         "    <CHOICE>Fresh fruit</CHOICE>"

   +         "    <CHOICE>Sorbet</CHOICE>"

   +         "</CHOICES>"

   + "</Field>";

Field choiceField = demoList.Fields.AddFieldAsXml(schemaChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Checkboxes

When creating Choice fields  in the user interface, you also have the option to display checkboxes to allow more than one selection:

To achieve this in code you have to set the Type attribute to MultiChoice. Of course, don't specify the Format attribute.

string schemaChoiceField = "<Field ID='<GUID>' Type='MultiChoice' Name='SideDishesChoice' StaticName='SideDishesChoice'

DisplayName = 'Side dishes' >"

+ "<Default>Patatoes</Default>"

   +         "<CHOICES>"

   +         "    <CHOICE>Fresh vegetables</CHOICE>"

   +         "    <CHOICE>Beans</CHOICE>"

+ " <CHOICE>Pepper Sauce</CHOICE>"

   +         "</CHOICES>"

+ "</Field>";

Field choiceField = demoList.Fields.AddFieldAsXml(schemaChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Fill In option

To allow users to fill in a different choice than already available, you have to add the FillInChoice attribute. If that attribute is omitted in the XML,  users will only be able to choose from the available options.

string schemaChoiceField = "<Field ID='<GUID>' Type='Choice' DisplayName='Menu Choice' Name='MenuChoice' StaticName='MenuChoice'

Format='Dropdown' FillInChoice='TRUE'>"

+ "<Default>Meat menu</Default>"

   +         "<CHOICES>"

   +         "    <CHOICE>Fish menu</CHOICE>"

   +         "    <CHOICE>Vegeterian menu</CHOICE>"

   +         "</CHOICES>"

+ "</Field>";

Field choiceField = demoList.Fields.AddFieldAsXml(schemaChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Create a Picture field

If you want to create a picture field, you have to set the field type to URL. An additional attribute Format will indicate that you want to create a picture field:

string schemaPictureField = "<Field ID='<GUID>' Type='URL' Name='EmployeePicture' StaticName='EmployeePicture'

DisplayName='Employee Picture' Format='Image'/>";

Field pictureField = demoList.Fields.AddFieldAsXml(schemaPictureField, true, AddFieldOptions.AddInternalNameHint);

clientContext.ExecuteQuery();

Create a URL field

If you want to create a field to contain an hyperlink, you also have to define a field of type URL, but in that case you set the Format attribute to Hyperlink:

string schemaUrlField = "<Field ID='<GUID>' Type='URL' Name='BlogUrl' StaticName='BlogUrl' DisplayName='Blog URL' Format='Hyperlink'/>";

Field urlField = demoList.Fields.AddFieldAsXml(schemaPictureField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Create a Lookup field

You typically create a lookup field when the value needs to be looked up in another SharePoint list. When creating a Lookup field, you also need to specify the necessary attributes to indicate the lookup list and the field that is shown when a value is selected:

string schemaLookupField = "<Field ID ='<GUID>' Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country'

   List='Countries' ShowField='Title' />"

Field lookupField = demoList.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

If you want to show another field from the lookup list, instead of the Title, you can set the ShowField attribute to another field.

You can also define how the relationship with the lookup field must behave.  But in that case the field needs to be indexed:

string schemaLookupField = "<Field ID ='<GUID>' Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country'

    List='Countries' ShowField='Title' RelationshipDeleteBehavior='Restrict' Indexed='TRUE'/>"

If you want to create a multi-select lookup field, you have to use the type LookupMulti, and you have to set an additional attribute Mult (and not Multi):

string schemaMultiLookupField = "<Field ID ='<GUID>' Type='LookupMulti' Name='Country' StaticName='Country' DisplayName='Country'

    List='Countries' ShowField='Title' Mult='TRUE'/>"

Create a User field

A field of type User is defined as follows:

string schemaUserField = "<Field ID ='<GUID>' Type='User' Name='Employee' StaticName='Employee' DisplayName='Employee' />"

Field userField = demoList.Fields.AddFieldAsXml(schemaUserField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

You can set different attributes:

  • UserSelectionMode: this attribute can be set to PeopleOnly or to PeopleAndGroups
  • UserSelectionScope: this attribute can be set to limit the selection of possible users to a certain group. The value must be an integer value that indicates the ID of group

Following code sample defines a user field that allows selection of multiple users from the site member group:

string schemaUserField = "<Field ID ='<GUID>' Type='UserMulti' Name='Employee' StaticName='Employee' DisplayName='Employee'

UserSelectionMode='PeopleOnly' UserSelectionScope='7' Mult='TRUE'/>"

Create a Managed Metadata field

The creation of a managed metadata field requires a bit more than just defining the CAML. I'll add it here for completeness, but credits are for Waldek Mastykarz with his post Programmatically creating Site Columns and Content Types using the App Model

string schemaTaxonomyField = "<Field ID ='<GUID>' Type='TaxonomyFieldType' Name='ProductCategory' StaticName='ProductCategory'

DisplayName='ProductCategory' />"

Field field = demoList.Fields.AddFieldAsXml(schemaTaxonomyField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Of course, this is not enough; you also have to bind this field to a termset or term in the term store:

Guid termStoreId = Guid.Empty;

Guid termSetId = Guid.Empty;

GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId);

 
 

// Retrieve the field as a Taxonomy Field

TaxonomyField taxonomyField = clientContext.CastTo<TaxonomyField>(field);

taxonomyField.SspId = termStoreId;

taxonomyField.TermSetId = termSetId;

taxonomyField.TargetTemplate = String.Empty;

taxonomyField.AnchorId = Guid.Empty;

taxonomyField.Update();

 
 

clientContext.ExecuteQuery();

In case you want to create a multi-select managed metadata field, you have to define a field of type TaxonomyFieldTypeMulti.

Create a Calculated field

Calculated fields can be created in a number of flavors. The following code snippet generates a calculated field that will show employee data based on the fields FirstName, LastName and EmployeeID. It will be formatted as follows:

Karine Bosch (id 82176)

string formula = "<Formula>=FirstName&amp; \" \" &amp;LastName&amp; \" (id: \" &amp;EmployeeID&amp; \" \"</Formula>"

      + "<FieldRefs>"

      + "<FieldRef Name='FirstName' />"

      + "<FieldRef Name='LastName' />"

      + "<FieldRef Name='EmployeeID' />"

      + "</FieldRefs>";

 

string schemaCalculatedField = "<Field ID='<GUID>' Type='Calculated' Name='FullName' StaticName='FullName'

DisplayName='Full Name' ResultType='Text' Required='TRUE' ReadOnly='TRUE'>" + formula + "</Field>";

Field fullNameField = demoList.Fields.AddFieldAsXml(schemaCalculatedField, true, AddFieldOptions.AddFieldInternalNameHint);

clientContext.ExecuteQuery();

Another example is a field that defaults to the year number of todays' date. In this case the element <DefaultFormula> is used within a Text field:

string fieldXml = "<Field DisplayName='Year' Type='Text'>"

+ "<DefaultFormula>=CONCATENATE(YEAR(Today))</DefaultFormula>"

+ "</Field>";

Field field = list.Fields.AddFieldAsXml(fieldXml, true,

AddFieldOptions.defaultValue);

context.ExecuteQuery();

Kudos to Steve Moucheron, who sent me his code snippet!

Creating fields using CSOM的更多相关文章

  1. Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form ResumeForm needs updating.

    django 报错 django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fiel ...

  2. Creating a SharePoint Sequential Workflow

    https://msdn.microsoft.com/en-us/library/office/hh824675(v=office.14).aspx Creating a SharePoint Seq ...

  3. Creating a radius based VPN with support for Windows clients

    This article discusses setting up up an integrated IPSec/L2TP VPN using Radius and integrating it wi ...

  4. Working With Taxonomy Field in CSOM

    How to create taxonomy field with CSOM If you need to programmatic create a taxonomy field, you need ...

  5. Resource annotation is not supported on static fields

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'paramUtil' d ...

  6. Creating a SharePoint BCS .NET Connectivity Assembly to Crawl RSS Data in Visual Studio 2010

    from:http://blog.tallan.com/2012/07/18/creating-a-sharepoint-bcs-net-assembly-connector-to-crawl-rss ...

  7. ASP.NET MVC3 Dynamically added form fields model binding

    Adding  new Item to a list of items, inline is a very nice feature you can provide to your user. Thi ...

  8. Copying Fields to a new Record

    This is a time saving tip for application designer. If you are creating a new record definition and ...

  9. Creating SharePoint 2010 Event Receivers in Visual Studio 2010

    转:http://msdn.microsoft.com/en-us/library/gg252010(v=office.14).aspx Summary:  Learn how to create a ...

随机推荐

  1. 鸟哥的Linux私房菜 基础学习篇读书笔记(9):Linux磁盘与文件系统管理(2)

    上一篇文章主要从理论上分析了Linux的Ext2文件系统.这一篇主要解说怎样查看Linux的文件系统的容量以及解说Linux文件系统中的连接文件. 能够通过df和du命令来查看磁盘与文件夹的容量.df ...

  2. 在Delphi中DBGrid有一个MouseMove事件,当鼠标移动时怎么知道光标在哪个单元格上面

    procedure TForm1.DBGrid1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);var coords:TGr ...

  3. 一个完整的DLL远程注入函数

    函数名称: CreateRemoteDll() 返加类型:BOOL 接受参数: DLL路径,注入进程ID 其完整代码如下: BOOL CreateRemoteDll(const char *DllFu ...

  4. Objective-C中的一些特殊的数据类及NSLog的输出格式

    NSLog的格式如下所示: %@     对象 %d, %i 整数 %u     无符整形 %f     浮点/双字 %x, %X 二进制整数 %o     八进制整数 %zu    size_t % ...

  5. android studio每次启动都要在fetching Android sdk compoment information停好久 怎么解决?

    网上有人给出了方案:1)进入刚安装的Android Studio目录下的bin目录.找到idea.properties文件,用文本编辑器打开.2)在idea.properties文件末尾添加一行: d ...

  6. Quartz:不要重复造轮子,一款企业级任务调度框架。

    背景 第一次遇到定时执行某些任务的需求时,很多朋友可能设计了一个小类库,这个类图提高了一个接口,然后由调度器调度所有注册的接口类型,我就是其中之一,随着接触的开源项目越来越多,我的某些开发习惯受到了影 ...

  7. JForum 源码分析

    怎么才算好的源码分析呢?当然我这个肯定不算.我想大概分为几个层面吧,写写注释那算最基本的了,写写要点思路和难点,算是还不错拉,再难的就是跳出源码举一反三,形成自己的一套思路吧.好好努力吧. 这次针对的 ...

  8. IT狂人第一至四季/全集The IT Crowd迅雷下载

    本季第一至四季 The IT Crowd (2006)看点:<IT狂人>史上最囧,最雷,最脑残,最出乎意料,最不按常理出牌的IT “精英们”登上银屏了.让超擅长收发邮件.单击和双击鼠标的I ...

  9. Android中获取屏幕长宽的方法

    package com.kale.screen; import android.annotation.SuppressLint; import android.app.Activity; import ...

  10. java的反射机制浅谈(转)

    原文链接:java的反射机制浅谈 一.java的反射机制浅谈 1.何谓反射机制 根据网文,java中的反射机制可以如此定义: JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性 ...