private static bool TryHideField(SPList list, string InternalName) { SPField field = null; try { field = list.Fields.GetFieldByInternalName(InternalName); } catch { } if (field != null) { try { if (field.Sealed) { field.Sealed = false; field.Update(); } field.Hidden = true; field.Update(); list.Update(); return(true); } catch { return(false); } } else { return(true); } }
/// <summary> /// Modifies the fields. /// </summary> /// <param name="enabled">if set to <c>true</c> [enabled].</param> private void ModifyFields(bool enabled) { try { SPField field = _list.Fields.GetFieldByInternalName(UrlField); field.ShowInNewForm = !enabled; field.ShowInEditForm = !enabled; field.ReadOnlyField = enabled; field.ShowInDisplayForm = enabled; field.Update(); if (OptHideTemplateField) { field = _list.Fields.GetFieldByInternalName(TemplateField); field.ShowInNewForm = !enabled; field.ShowInEditForm = !enabled; field.ReadOnlyField = enabled; field.ShowInDisplayForm = enabled; field.Update(); } } catch (ArgumentException ex) { Debug.WriteLine(ex); } }
public static void SaveCustomAttribute(this SPField sField, string propertyName, object propertyValue) { if (sField != null) { try { Type type = typeof(SPField); if (propertyValue != null) { MethodInfo set = type.GetMethod("SetFieldAttributeValue", BindingFlags.NonPublic | BindingFlags.Instance); set.Invoke(sField, new object[] { propertyName, propertyValue.ToString() }); sField.Update(); } else { MethodInfo remove = type.GetMethod("RemoveFieldAttributeValue", BindingFlags.NonPublic | BindingFlags.Instance); remove.Invoke(sField, new object[] { propertyName }); sField.Update(); } } catch { } } }
public override void DeployModel(object modelHost, DefinitionBase model) { ModelHost = modelHost; CheckValidModelHost(modelHost); var fieldModel = model.WithAssertAndCast <FieldDefinition>("model", value => value.RequireNotNull()); SPField field = null; // TODO, needs to be changed to using pattern and adjust all model handlers InvokeOnModelEvent <FieldDefinition, SPField>(field, ModelEventType.OnUpdating); var isListField = false; if (modelHost is SiteModelHost) { field = DeploySiteField((modelHost as SiteModelHost).HostSite, fieldModel); } else if (modelHost is WebModelHost) { field = DeployWebField((modelHost as WebModelHost).HostWeb, fieldModel); isListField = true; } else if (modelHost is ListModelHost) { field = DeployListField((modelHost as ListModelHost).HostList, fieldModel); isListField = true; } else { throw new ArgumentException("modelHost needs to be SiteModelHost/WebModelHost/ListModelHost"); } ProcessFieldProperties(field, fieldModel); InvokeOnModelEvent(this, new ModelEventArgs { CurrentModelNode = null, Model = null, EventType = ModelEventType.OnProvisioned, Object = field, ObjectType = GetTargetFieldType(fieldModel), ObjectDefinition = fieldModel, ModelHost = modelHost }); InvokeOnModelEvent <FieldDefinition, SPField>(field, ModelEventType.OnUpdated); // no promotion for the list field, and force push for the site fields if (isListField) { field.Update(); } else { field.Update(true); } }
public static void EnableTimesheets(SPList list, SPWeb web) { TryAddField(list, "Timesheet", SPFieldType.Boolean, "Timesheet", false); TryAddField(list, "TimesheetHours", SPFieldType.Number, "Timesheet Hours", false); SPField field = list.Fields.GetFieldByInternalName("TimesheetHours"); field.ShowInEditForm = false; field.ShowInNewForm = false; field.Hidden = false; field.Update(); field = list.Fields.GetFieldByInternalName("Timesheet"); field.Hidden = false; field.Update(); try { SPContentType defaultContentType = list.ContentTypes["Item"]; { if (field != null) { SPFieldLink fld = new SPFieldLink(field); if (fld != null) { if (defaultContentType.FieldLinks[fld.Id] == null) { defaultContentType.FieldLinks.Delete(fld.Name); defaultContentType.Update(); defaultContentType.FieldLinks.Add(fld); defaultContentType.Update(); list.Update(); } } } } } catch { } try { SPWeb rootWeb = web.Site.RootWeb; ArrayList lists = new ArrayList(EPMLiveCore.CoreFunctions.getConfigSetting(rootWeb, "EPMLiveTSLists").Replace("\r\n", "\n").Split('\n'));; if (!lists.Contains(list.Title)) { lists.Add(list.Title); EPMLiveCore.CoreFunctions.setConfigSetting(rootWeb, "EPMLiveTSLists", String.Join("\n", (string[])lists.ToArray(typeof(string))).Replace("\n", "\r\n")); } } catch { } }
public void Update(object pushChangesToLists) { if (pushChangesToLists == null || pushChangesToLists == Null.Value || pushChangesToLists == Undefined.Value) { m_field.Update(); } else { m_field.Update(TypeConverter.ToBoolean(pushChangesToLists)); } }
//在数据保存的时候,将操作字段隐藏 private void SetActionField(SPItemEventProperties properties) { string fldName = "Action"; SPWeb spWeb1 = properties.Web; if (properties.List.Fields.ContainsFieldWithStaticName(fldName)) { SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite spSite = new SPSite(spWeb1.Site.ID)) //找到网站集 { using (SPWeb spWeb = spSite.OpenWeb(spWeb1.ID)) { SPList lst = spWeb.Lists.TryGetList(properties.List.Title); SPField fld = lst.Fields.GetFieldByInternalName(fldName); fld.ShowInDisplayForm = false; fld.ShowInEditForm = false; fld.ShowInNewForm = false; spWeb.AllowUnsafeUpdates = true; fld.Update(); spWeb.AllowUnsafeUpdates = false; } } }); } }
private void CreateExtractorTranslationsColumns() { var obj = new Helper(SiteUrl, WebUrl, ListName); var ht = new Hashtable(); foreach (string twoLetterIso in Languages.Instance.AllLanguages) { var fieldTwoLetterIso = new FieldObject(string.Empty, FieldObject.Types.Note, false); ht.Add(twoLetterIso, fieldTwoLetterIso); } obj.AddFields(ht); using (var site = new SPSite(SiteUrl)) { using (SPWeb web = site.OpenWeb()) { SPList sharepointList = web.GetList("Lists/ExtractorTranslations/AllItems.aspx"); SPFieldCollection fieldCollection = sharepointList.Fields; var sharepointFieldTitle = new SPField(fieldCollection, "Title") { ReadOnlyField = true, Required = false }; sharepointFieldTitle.Update(); } } }
public static void CreateListStructure(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.DisplayName.WebsiteLink, Name = ListsName.InternalName.WebsiteLink, OnQuickLaunch = false, EnableAttachments = true }; helper.AddField(new SingleLineTextFieldCreator(FieldsName.WebsiteLink.InternalName.Description, FieldsName.WebsiteLink.DisplayName.Description)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.WebsiteLink.InternalName.Status, FieldsName.WebsiteLink.DisplayName.Status)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.WebsiteLink.InternalName.WebURL, FieldsName.WebsiteLink.DisplayName.WebURL)); SPList list = helper.Apply(); SPField fieldTitle = list.Fields.GetField(FieldsName.WebsiteLink.InternalName.Title); if (fieldTitle != null) { fieldTitle.Title = FieldsName.WebsiteLink.DisplayName.Title; fieldTitle.Update(); } list.Update(); var defaultView = list.DefaultView; defaultView.ViewFields.DeleteAll(); defaultView.RowLimit = 100; defaultView.ViewFields.Add(Constants.EditColumn); defaultView.ViewFields.Add(Constants.FieldTitleLinkToItem); defaultView.ViewFields.Add(FieldsName.WebsiteLink.InternalName.WebURL); defaultView.ViewFields.Add(FieldsName.WebsiteLink.InternalName.Status); defaultView.Update(); }
public static void RenameField(this SPField fieldName, string newFieldName) { try { var originalUICulture = Thread.CurrentThread.CurrentUICulture; SPSecurity.RunWithElevatedPrivileges(delegate() { if (SPContext.Current == null) { Thread.CurrentThread.CurrentUICulture = new CultureInfo((int)fieldName.ParentList.ParentWeb.Language); } fieldName.Title = newFieldName; fieldName.PushChangesToLists = true; fieldName.Update(true); fieldName.ParentList.Update(); Thread.CurrentThread.CurrentUICulture = originalUICulture; }); } catch (Exception ex) { Log.Error(ex); } }
void AddFields() { SPField assignmentId = AddField(DropBox.ColumnAssignmentId, SPFieldType.Text, false); assignmentId.Indexed = true; assignmentId.Update(); dropBoxList.Update(); web.Update(); AddField(DropBox.ColumnAssignmentDate, SPFieldType.DateTime, true); AddField(DropBox.ColumnAssignmentName, SPFieldType.Text, true); AddField(DropBox.ColumnIsLatest, SPFieldType.Boolean, true); AddField(DropBox.ColumnLearner, SPFieldType.User, true); AddField(DropBox.ColumnLearnerId, SPFieldType.Text, false); dropBoxList.Update(); web.Update(); SPFieldCalculated assignmentKey = (SPFieldCalculated)AddField(DropBox.ColumnAssignmentKey, SPFieldType.Calculated, true, false); // The formula depends on the regional settings of the web, notably the list separator required. // So for a standard english site the formula will be // =TEXT(AssignmentDate,"yyyy-mm-dd")&" "&AssignmentName // but for many regions, notably Europe, the list separator is ; so the formula needs to be // =TEXT(AssignmentDate;"yyyy-mm-dd")&" "&AssignmentName // SharePoint automatically converts formulae when you change the regional settings. Originally the code changed the web Locale before adding the fields // and then changed back at the end, but this is simpler, and in some environments that change caused errors which prevented any fields being added. string formula = "=TEXT([{0}]{2} \"yyyy-mm-dd\")&\" \"&[{1}]"; assignmentKey.Formula = string.Format(formula, DropBox.ColumnAssignmentDate, DropBox.ColumnAssignmentName, web.Locale.TextInfo.ListSeparator); assignmentKey.Update(); dropBoxList.Update(); web.Update(); }
/// <summary> /// /// </summary> /// <param name="web"></param> /// <param name="listTitle"></param> /// <param name="fieldName"></param> /// <param name="allow"></param> /// <reference>https://msdn.microsoft.com/en-us/library/office/ee536168(v=office.14).aspx</reference> public static void AllowDuplicateValues(SPWeb web, string listTitle, string fieldName, bool allow = true) { runCodeInListInstance(web, listTitle, (list) => { if (list.ItemCount > 0 && !allow) { Logger.Unexpected("ListUtils.AllowDuplicateValues", "Could not allow duplicate values for the field \"{0}\" list \"{1}\" because it contains items. Remove all items from the list.", fieldName, listTitle); return; } if (list.Fields.ContainsField(fieldName)) { SPField field = list.Fields[fieldName]; field.Indexed = !allow; //field.AllowDuplicateValues = false; field.EnforceUniqueValues = !allow; field.Update(); list.Update(); var message = "The \"{0}\" field no longer allows duplicate values"; if (!allow) { message = "The \"{0}\" field allows duplicate values"; } Logger.Information("ListUtils.AllowDuplicateValues", message, fieldName); } }); }
private void CreateLangVisibilityColumns() { var obj = new Helper(SiteUrl, WebUrl, ListName); var ht = new Hashtable(); var field = new FieldObject(string.Empty, FieldObject.Types.Text, true); ht.Add("LanguageCode", field); field = new FieldObject(string.Empty, FieldObject.Types.Boolean, true); ht.Add("IsVisible", field); field = new FieldObject(string.Empty, FieldObject.Types.Boolean, true); ht.Add("DefaultLanguage", field); field = new FieldObject(string.Empty, FieldObject.Types.Text, true); ht.Add("LanguagesDisplay", field); field = new FieldObject(string.Empty, FieldObject.Types.Text, false); ht.Add("LanguagesPicture", field); obj.AddFields(ht); using (var site = new SPSite(SiteUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList("Lists/LanguagesVisibility/AllItems.aspx"); SPFieldCollection fieldCollection = list.Fields; var fieldLanguageCode = new SPField(fieldCollection, "LanguageCode") { ReadOnlyField = true }; fieldLanguageCode.Update(); } } }
public static void CreateListStructure(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.DisplayName.SignaturePerson, Name = ListsName.InternalName.SignaturePerson, OnQuickLaunch = false, EnableAttachments = true }; SPList list = helper.Apply(); SPField fieldTitle = list.Fields.GetField(FieldsName.SignaturePerson.InternalName.Title); if (fieldTitle != null) { fieldTitle.Title = FieldsName.SignaturePerson.DisplayName.Title; fieldTitle.Update(); } list.Update(); var defaultView = list.DefaultView; defaultView.ViewFields.DeleteAll(); defaultView.RowLimit = 100; defaultView.ViewFields.Add(Constants.EditColumn); defaultView.ViewFields.Add(Constants.FieldTitleLinkToItem); defaultView.Update(); }
protected virtual void AddFieldTo(SPFieldCollection fieldCollection, Action <SPField> fieldAction) { SPField newField = null; if (ID != System.Guid.Empty && fieldCollection.Web.AvailableFields.Contains(ID)) { SPField field = fieldCollection.Web.AvailableFields[ID]; fieldCollection.Add(field); newField = fieldCollection[ID]; } else { newField = CreateField(fieldCollection); } if (fieldAction != null) { fieldAction(newField); } if (!string.IsNullOrEmpty(Title)) { newField.Title = Title; } if (!string.IsNullOrEmpty(Description)) { newField.Description = Description; } newField.Update(); }
public static void CreateListStructure(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.DisplayName.StatisticsList, Name = ListsName.InternalName.StatisticsList, OnQuickLaunch = false, EnableAttachments = false }; helper.AddField(new SingleLineTextFieldCreator(FieldsName.StatisticsList.InternalName.UserBrowser, FieldsName.StatisticsList.DisplayName.UserBrowser)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.StatisticsList.InternalName.UserIP, FieldsName.StatisticsList.DisplayName.UserIP)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.StatisticsList.InternalName.UserUrl, FieldsName.StatisticsList.DisplayName.UserUrl)); SPList list = helper.Apply(); SPField fieldTitle = list.Fields.GetField(FieldsName.StatisticsList.InternalName.Title); if (fieldTitle != null) { fieldTitle.Title = FieldsName.StatisticsList.DisplayName.Title; fieldTitle.Update(); } list.Update(); var defaultView = list.DefaultView; defaultView.ViewFields.DeleteAll(); defaultView.RowLimit = 100; defaultView.Query = "<OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>"; defaultView.ViewFields.Add(Constants.FieldTitleLinkToItem); defaultView.ViewFields.Add(FieldsName.StatisticsList.InternalName.UserBrowser); defaultView.ViewFields.Add(FieldsName.StatisticsList.InternalName.UserIP); defaultView.ViewFields.Add(FieldsName.StatisticsList.InternalName.UserUrl); defaultView.Update(); }
public override void OnDeleting() { base.OnDeleting(); string fields = string.Empty; if (this.GetCustomProperty(CustomDropDownList.ADDITIONAL_FIELDS) != null) { fields = Convert.ToString(this.GetCustomProperty(CustomDropDownList.ADDITIONAL_FIELDS)); } if ((base.ParentList != null) && !string.IsNullOrEmpty(fields)) { SPWeb w = SPContext.Current.Site.OpenWeb(this.LookupWebId); SPList sourceList = w.Lists[new Guid(this.LookupList)]; SPList currentList = SPContext.Current.List; foreach (string str in fields.Split(';')) { string str2 = this.InternalName + ":" + sourceList.Fields[new Guid(str)].Title; if (str2.Length > 0x20) { str2 = str2.Substring(0, 0x20); } if (currentList.Fields.ContainsField(str2)) { SPField fieldByInternalName = currentList.Fields[str2] as SPFieldLookup; fieldByInternalName.ReadOnlyField = false; fieldByInternalName.Update(); base.ParentList.Fields.Delete(str2); } } } }
public static void Setup(SPWeb web) { SPList list = web.Lists.TryGetList(listName); //ukryj kolumnę serwisy dla nowych rekordów SPField f = null; try { f = list.Fields["selSewisy"]; } catch (Exception) {} if (f == null) { try { f = list.Fields["Serwisy"]; } catch (Exception) {} } if (f != null) { f.ShowInNewForm = false; f.Update(); list.Update(); } }
// Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPWeb currentWeb = properties.Feature.Parent as SPWeb; SPList classesList = currentWeb.Lists["Classes"]; SPField titleField = classesList.Fields["Title"]; titleField.Required = false; titleField.ShowInNewForm = false; titleField.ShowInEditForm = false; titleField.Title = "Class ID"; titleField.Update(); SPField registrationsField = classesList.Fields["Registrations"]; registrationsField.DefaultValue = "0"; registrationsField.ShowInNewForm = false; registrationsField.Update(); SPFieldDateTime startDate = currentWeb.Fields["Start Date"] as SPFieldDateTime; startDate.DisplayFormat = SPDateTimeFieldFormatType.DateTime; SPFieldDateTime endDate = currentWeb.Fields["End Date"] as SPFieldDateTime; endDate.DisplayFormat = SPDateTimeFieldFormatType.DateTime; classesList.Fields.Add(startDate); classesList.Fields.Add(endDate); SPView defaultView = classesList.DefaultView; defaultView.ViewFields.Add(startDate); defaultView.ViewFields.Add(endDate); defaultView.Update(); classesList.Update(); }
private void AddColumn() { using (SPSite eleSite = new SPSite(Web.Url)) { eleSite.AllowUnsafeUpdates = true; using (SPWeb eleWeb = eleSite.OpenWeb()) { eleWeb.AllowUnsafeUpdates = true; SPList list = eleWeb.Lists["Resources"]; string id = list.Fields.Add("UserHasPermission", SPFieldType.Boolean, false); SPField spfield = (SPField)list.Fields.GetField(id); spfield.Hidden = true; spfield.Update(); SPView view = list.DefaultView; view.ViewFields.Add("UserHasPermission"); view.Update(); eleWeb.AllowUnsafeUpdates = false; } eleSite.AllowUnsafeUpdates = false; } }
private void AddTaskCenterField(SPField field, CustomFieldDataSet customFieldDataSet, DictionaryEntry dictionaryEntry) { if (field != null) { if (field.Type == SPFieldType.Choice) { using (var command = new SqlCommand("select * from customfields where wssfieldname=@fieldname and fieldcategory=3", cn)) { command.Parameters.AddWithValue("@fieldname", field.InternalName); using (var dataReader = command.ExecuteReader()) { if (dataReader.Read()) { field.SchemaXml = getSchemaXml(field, dataReader.GetString(0)); } } } } if (isCalculated(customFieldDataSet, dictionaryEntry.Key.ToString().Substring(3))) { field.ShowInEditForm = false; field.ShowInNewForm = false; } field.Update(); } }
private static bool TryAddField(SPList list, string InternalName, SPFieldType type, string Title, bool Hidden) { SPField field = null; try { field = list.Fields.GetFieldByInternalName(InternalName); } catch { } if (field == null) { try { string sField = list.Fields.Add(InternalName, type, false); field = list.Fields.GetFieldByInternalName(InternalName); field.Title = Title; field.Hidden = Hidden; field.Update(); return(true); } catch { return(false); } } else { return(true); } }
public static void CreateListStructure(SPWeb web) { var helper = new ListHelper(web) { Title = ListsName.DisplayName.VideoLibrary, Name = ListsName.InternalName.VideoLibrary, OnQuickLaunch = false, EnableAttachments = true }; helper.AddField(new SingleLineTextFieldCreator(FieldsName.VideoLibrary.InternalName.Description, FieldsName.CategoryList.DisplayName.Description)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.VideoLibrary.InternalName.AlbumId, FieldsName.VideoLibrary.DisplayName.AlbumId)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.VideoLibrary.InternalName.CategoryId, FieldsName.VideoLibrary.DisplayName.CategoryId)); helper.AddField(new NumberFieldCreator(FieldsName.VideoLibrary.InternalName.Status, FieldsName.VideoLibrary.DisplayName.Status)); helper.AddField(new NumberFieldCreator(FieldsName.VideoLibrary.InternalName.Order, FieldsName.VideoLibrary.DisplayName.Order)); helper.AddField(new SingleLineTextFieldCreator(FieldsName.VideoLibrary.InternalName.FilePath, FieldsName.VideoLibrary.DisplayName.FilePath)); SPList list = helper.Apply(); SPField fieldTitle = list.Fields.GetField(FieldsName.VideoLibrary.InternalName.Title); if (fieldTitle != null) { fieldTitle.Title = FieldsName.VideoLibrary.DisplayName.Title; fieldTitle.Update(); } list.Update(); }
private void CreatePagesToUpdateForTranslationColumns() { var obj = new Helper(SiteUrl, WebUrl, ListName); var ht = new Hashtable(); var field = new FieldObject(string.Empty, FieldObject.Types.Text, false); ht.Add("Pages", field); obj.AddFields(ht); using (var site = new SPSite(SiteUrl)) { using (SPWeb web = site.OpenWeb()) { SPList list = web.GetList("Lists/PagesToUpdateForTranslation/AllItems.aspx"); SPFieldCollection fieldCollection = list.Fields; var fieldTitle = new SPField(fieldCollection, "Title") { ReadOnlyField = true, Required = false }; fieldTitle.Update(); } } }
/// <summary> /// 如果活动列表不存在,自动创建 /// </summary> private SPList CreateActivityList(Guid siteID, Guid webID, string lstTitle, string desc, string lookupListTitle) { SPList retList = null; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb oWebsite = new SPSite(siteID).AllWebs[webID]) { oWebsite.AllowUnsafeUpdates = true; try { oWebsite.Lists.Add(lstTitle, desc, SPListTemplateType.GenericList); SPList list = oWebsite.Lists[lstTitle]; SPField myField = list.Fields.GetFieldByInternalName("Title"); myField.Title = "活动名称"; myField.Update(); list.Fields.Add("活动类型", SPFieldType.Text, false); list.Fields.Add("活动地点", SPFieldType.Text, false); list.Fields.Add("活动对象", SPFieldType.Text, false); list.Fields.Add("开始时间", SPFieldType.DateTime, false); list.Fields.Add("持续时长", SPFieldType.Integer, false); list.Fields.Add("执行者", SPFieldType.User, false); list.Fields.Add("活动描述", SPFieldType.Text, false); list.Fields.Add("作品地址", SPFieldType.Text, false); string fieldName = "计划ID"; //新增的Lookup类型字段的名字 SPList lookupList = oWebsite.Lists[lookupListTitle]; //设置这个Lookup类型字段要从哪个List中去取值 Guid lookupGuid = new Guid(lookupList.ID.ToString()); // 取得这个Lookup数据源List的Guid list.Fields.AddLookup(fieldName, lookupGuid, false); //把上面取得的参数引入到AddLookup方法中,从而创建一个Lookup字段 SPFieldLookup splookup = list.Fields[fieldName] as SPFieldLookup; //绑定数据List到Lookup字段 splookup.LookupField = "Title"; splookup.Update(); SPView defaultView = list.Views[0]; defaultView.ViewFields.Add(list.Fields["活动地点"]); defaultView.ViewFields.Add(list.Fields["活动类型"]); defaultView.ViewFields.Add(list.Fields["活动对象"]); defaultView.ViewFields.Add(list.Fields["开始时间"]); defaultView.ViewFields.Add(list.Fields["持续时长"]); defaultView.ViewFields.Add(list.Fields["执行者"]); defaultView.ViewFields.Add(list.Fields["活动描述"]); defaultView.ViewFields.Add(list.Fields["作品地址"]); defaultView.ViewFields.Add(list.Fields["计划ID"]); defaultView.Update(); list.Update(); retList = list; } catch { } oWebsite.AllowUnsafeUpdates = false; } }); return(retList); }
protected void KillTitleField() { SPField title = List.Fields.GetField(TitleField); title.Required = false; title.Hidden = true; title.Update(); }
/// <summary> /// Indicates whether field will indexed. /// </summary> /// <param name="field"></param> public static void CreateIndexedField(SPField field) { if (!field.Indexed) { field.Indexed = true; field.Update(); } }
private int FieldExist(int parentMessageId, string internalName, string field, bool overwrite, string listId, SPField spField) { if (spField == null) { throw new ArgumentNullException(nameof(spField)); } int messageId; if (spField.Type == SPFieldType.Lookup) { if (bVerifyOnly) { if (overwrite) { messageId = addMessage(ErrorLevels.Upgrade, internalName, "Field exists and will overwrite", parentMessageId); } else { messageId = addMessage(ErrorLevels.Error, internalName, "Field exists and will not overwrite", parentMessageId); } } else { if (overwrite) { try { var doc = new XmlDocument(); doc.LoadXml(spField.SchemaXml); doc.FirstChild.Attributes["List"].Value = listId; doc.FirstChild.Attributes["ShowField"].Value = field; spField.SchemaXml = doc.FirstChild.OuterXml; spField.Update(true); messageId = addMessage(0, internalName, "Field updated", parentMessageId); } catch (Exception ex) { messageId = addMessage(ErrorLevels.Error, internalName, "Error updating field: " + ex.Message, parentMessageId); Trace.WriteLine(ex.ToString()); } } else { messageId = addMessage(ErrorLevels.Error, internalName, "Field exists and will not overwrite", parentMessageId); } } } else { messageId = addMessage(ErrorLevels.Error, internalName, "Field exists and is not currently a lookup field", parentMessageId); } return(messageId); }
public static void InstallListFieldSwapXml(SPList list, SPField field, XmlNode ndNewField) { var bIsSealed = field.Sealed; if (bIsSealed) { field.Sealed = false; field.Update(); } InstallListFieldSwapXml(list, field.InternalName, ndNewField); if (bIsSealed) { field.Sealed = bIsSealed; field.Update(true); } }
private void UpdateField(string sFieldName, bool bCanShowInNewForm, bool bCanShowInEditForm, bool bCanShowInDisplayForm, ref SPList ResourcePool) { using (var spSite = new SPSite(ResourcePool.ParentWeb.Site.ID)) { using (SPWeb spWeb = spSite.OpenWeb(ResourcePool.ParentWeb.ID)) { SPList oResourcePool = spWeb.Lists[ResourcePool.ID]; if (!oResourcePool.Fields.ContainsFieldWithInternalName(sFieldName)) { return; } try { SPField oField = oResourcePool.Fields.GetFieldByInternalName(sFieldName); bool bSealed = oField.Sealed; if (bSealed) { oField.Sealed = false; oField.Update(); } oField.ShowInDisplayForm = bCanShowInDisplayForm; oField.ShowInEditForm = bCanShowInEditForm; oField.ShowInNewForm = bCanShowInNewForm; oField.Update(); if (bSealed) { oField.Sealed = true; oField.Update(); } LogMessage("\t" + sFieldName); } catch (Exception ex) { LogMessage("", "(" + sFieldName + "): " + ex.Message, 3); } } } }
/// <summary> /// Set default value for a taxonomy site column /// </summary> /// <param name="web">The web.</param> /// <param name="field">The field.</param> /// <param name="termGroupName">The term group name.</param> /// <param name="termSetName">the term set name.</param> /// <param name="termLabel">The term label.</param> public void SetDefaultTaxonomyValue(SPWeb web, SPField field, string termGroupName, string termSetName, string termLabel) { var term = this._taxonomyService.GetTaxonomyValueForLabel(web.Site, termGroupName, termSetName, termLabel); var taxonomySession = new TaxonomySession(web.Site); TermStore termStore = taxonomySession.DefaultSiteCollectionTermStore; var termGroup = termStore.Groups[termGroupName]; var termSet = termGroup.TermSets[termSetName]; if (term != null) { var statusTaxonomyFieldDefaultValue = new TaxonomyFieldValue(field); string path = TaxonomyItem.NormalizeName(term.Label) + TaxonomyField.TaxonomyGuidLabelDelimiter + term.Id.ToString(); statusTaxonomyFieldDefaultValue.PopulateFromLabelGuidPair(path); int[] ids = TaxonomyField.GetWssIdsOfTerm(web.Site, termStore.Id, termSet.Id, term.Id, true, 1); if (ids.Length == 0) { statusTaxonomyFieldDefaultValue.WssId = -1; } statusTaxonomyFieldDefaultValue.TermGuid = statusTaxonomyFieldDefaultValue.TermGuid.ToUpperInvariant(); field.DefaultValue = statusTaxonomyFieldDefaultValue.ValidatedString; field.Update(); } }
static void FixupField(SPField spField) { // This method takes an InternalName of a field in a spList and process a few things we want all fields to have by default // for example setting them to show into the default view spField.ShowInDisplayForm = true; spField.ShowInEditForm = true; spField.ShowInListSettings = true; spField.ShowInNewForm = true; spField.ShowInVersionHistory = true; spField.ShowInViewForms = true; // Add field to default view SPView defaultView = spField.ParentList.DefaultView; defaultView.ViewFields.Add(spField); defaultView.Update(); spField.Update(); }
public static bool RemoveField(SPField spField) { bool res = false; try { if (spField == null) { return res; } // check if it's a ReadOnly field. // if so, reset it if (spField.ReadOnlyField) { spField.ReadOnlyField = false; spField.Update(); } // check if it's a Hidden field. // if so, reset it if (spField.Hidden) { spField.Hidden = false; spField.Update(); } // check if the AllowDeletion property is set to false. // if so, reset it to true if (spField.AllowDeletion == null || !spField.AllowDeletion.Value) { spField.AllowDeletion = true; spField.Update(); } // finally, remove the field spField.Delete(); spField.ParentList.Update(); res = true; } catch (Exception ex) { UlsLogging.LogError("ListField. RemoveField(SPField spField). Message: {0}, StackTrace: {1}", ex.Message, ex.StackTrace); } return res; }
public virtual void UpdateField(SPField field, bool pushChangesToList) { field.Update(pushChangesToList); }
// =========================================================================================================== /// <summary> /// Configures the TitleResource of the given <b>SPField</b> based on the specified <b>Field</b> config /// </summary> /// <param name="field">The <b>SPField</b> that needs to be configured</param> /// <param name="configField">The <b>Field</b> config</param> // =========================================================================================================== private void ConfigureFieldTitleResource(SPField field, Field configField) { logger.Info("Configuring title resources for field '{0}'", field.InternalName); foreach(TitleResource titleResource in configField.TitleResources) { field.TitleResource.SetValueForUICulture(new CultureInfo(titleResource.LCID), titleResource.Value); } field.Update(); }