SharePoint Tips

Sunday, March 13, 2016

Add metadata navigation settings to list c#

public static void AddFieldsToMDNSettings(SPList list)
        {
            // TODO: Replace these variable values and input parameters with your own values.
            //
            // internal name of the SPField to add into the key filters
            string fieldNameKeyFilterToAdd = "Modified";

            // Validate the input parameters.
            //
            if (null == list)
            {
                throw new System.ArgumentNullException("list");
            }

            // Get the MDN settings object for the SPList that was passed in.
            //
            MetadataNavigationSettings mdnSettings =
                MetadataNavigationSettings.GetMetadataNavigationSettings(list);

            // Add hiearchies into the settings if they are not already there
            //
            MetadataNavigationHierarchy folderHierarchyToAdd =
                MetadataNavigationHierarchy.CreateFolderHierarchy();
            if (null == mdnSettings.FindConfiguredHierarchy(folderHierarchyToAdd.FieldId))
            {
                mdnSettings.AddConfiguredHierarchy(folderHierarchyToAdd);
            }

            MetadataNavigationHierarchy contentTypeHierarchyToAdd =
                MetadataNavigationHierarchy.CreateContentTypeHierarchy();
            if (null == mdnSettings.FindConfiguredHierarchy(contentTypeHierarchyToAdd.FieldId))
            {
                mdnSettings.AddConfiguredHierarchy(contentTypeHierarchyToAdd);
            }

            // Add key filters into the settings if they are not already there
            //
            SPField newKeyFilterField = list.Fields[fieldNameKeyFilterToAdd];
            if (null == mdnSettings.FindConfiguredKeyFilter(newKeyFilterField.Id))
            {
                mdnSettings.AddConfiguredKeyFilter(new MetadataNavigationKeyFilter(newKeyFilterField));
            }

            MetadataNavigationKeyFilter contentTypeKeyFilter =
                MetadataNavigationKeyFilter.CreateContentTypeKeyFilter();
            if (null == mdnSettings.FindConfiguredKeyFilter(contentTypeKeyFilter.FieldId))
            {
                mdnSettings.AddConfiguredKeyFilter(contentTypeKeyFilter);
            }

            // Set the MDN settings back into the list and automatically adjust indexing.
            //
            MetadataNavigationSettings.SetMetadataNavigationSettings(list, mdnSettings, true);
        }

No comments:

Post a Comment