本文講述如何在SharePoint 2010/2013 中創建一個默認值爲當前用戶的客戶化字段。
在項目中我們經常會遇到客戶提出某個字段的默認設置爲當前用戶的需求,像這樣的需求一般來說有兩條路可以走:
1. 前端路線,大致思路是客戶化new form,使用JS取當前用戶,然後賦值到對應的字段,優缺點有:
a. 優點:前端代碼安全性好,不會對SharePoint server本身造成影響
b. 缺點:重用性不好,每次有這樣的需求只能拷貝代碼重用
2. 後臺路線,大致是寫個類繼承SPFieldUser,覆蓋其DefaultValue屬性,優缺點有:
a. 優點:重用性好,直接部署wsp就可以重用了
b. 缺點:用服務器端代碼,對SharePoint server有影響,寫得不好容易壞事
本文只講述後臺路線的步驟,因爲個人覺得重用性好更重要,更省時間:
1. 新建一個Farm Solution,命名爲 TestCurrentUserField
2. 添加SharePoint 映射路徑(Template\Xml)
3.新建一個CurrentUserField類繼承自SPFieldUser,CurrentUserField.cs代碼如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace TestCurrentUserField
{
class CurrentUserField : SPFieldUser
{
public CurrentUserField(SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName)
{
}
public CurrentUserField(SPFieldCollection fields, string fieldName):
base(fields, fieldName)
{
}
public override string DefaultValue
{
get
{
SPWeb web = SPContext.Current.Web;
SPUser user = web.CurrentUser;
string defaultValue = string.Format("{0};#{1}", user.ID.ToString(), user.Name);
if (this.SelectionGroup > 0)
{
SPGroup group = web.Groups[this.SelectionGroup];
if ((group != null) && (group.ContainsCurrentUser))
{
return defaultValue;
}
}
else
{
return defaultValue;
}
return string.Empty;
}
set
{
base.DefaultValue = value;
}
}
}
}
4. 在第二步添加的xml文件夾下添加 fldtypes_currentuser.xml,內容爲:
<?xml version="1.0" encoding="utf-8"?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">CurrentUser</Field>
<Field Name="ParentType">User</Field>
<Field Name="TypeDisplayName">Current User</Field>
<Field Name="TypeShortDescription">Person or Group (Current user is default)</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="ShowInListCreate">TRUE</Field>
<Field Name="ShowInSurveyCreate">TRUE</Field>
<Field Name="ShowInDocumentLibraryCreate">TRUE</Field>
<Field Name="ShowInColumnTemplateCreate">TRUE</Field>
<Field Name="FieldTypeClass">TestCurrentUserField.CurrentUserField,$SharePoint.Project.AssemblyFullName$</Field>
<Field Name="FieldEditorUserControl">/_controltemplates/UserFieldEditor.ascx</Field>
<PropertySchema>
</PropertySchema>
</FieldType>
</FieldTypes>
5. 部署解決方案,並新建一個測試列表,添加一個客戶化過的CurrentUserField
6.添加一條測試記錄,默認值就帶出來了
跟多客戶化字段的信息,請參考:
http://msdn.microsoft.com/en-us/library/office/bb861799(v=office.14).aspx