Responsive Ads Here

Tuesday, July 17, 2012

Set Default value to metadata column of a SharePoint List


If you want to set the default value of the a meta data column of a list through code you might encounter the “Out Of Range Exception”.
The field doesn’t recognize the term label as a valid value. This is because the value is actually stored as a lookup value on a hidden list named “TaxonomyHiddenList”.
When you use a term in your site collection for the first time an entry is made in this list with the following columns.


The value when used elsewhere will be a look up for this item.
If you want to set the default value, you have to use
SpField.DefaultValue = “String”;
String would be of the format :    ID;#<TermLabel>|<GUID of the term>

Where ID is the ID of the list item for the term in the hidden list and GUID the term in the term store.
For the above example it would be “15;#Review|b7df5b79-1190-45a3-8e5c-478c9372c15b”
So if we use SpField.DefaultValue =“15;#Review|b7df5b79-1190-45a3-8e5c-478c9372c15b”; it would work.


Code Snippet 

 TaxonomySession _TaxonomySession = new TaxonomySession(spSite);  
         //Get instance of the Term Store  
         TermStore _TermStore = _TaxonomySession.TermStores[Constants.ManagedMetaDataServiceAppName];  
         //Get instance of Group  
         Group group = _TermStore.Groups.FirstOrDefault(e => e.Name == Constants.AIPTermsGroup);  
         //Get the termset of projectType  
         TermSet termset_ProjectTerms = group.TermSets.FirstOrDefault(e => e.Name == Constants.ProjectTermsTermSet);  
         //Get the term --Project Type  
         Term term_ProjectName = termset_ProjectTerms.Terms.FirstOrDefault(e => e.Name == Constants.TermProject);  
         //Check for Project Type not emptty  
         if (!string.IsNullOrEmpty(projectShortName))  
         {  
           //Check whether the current projects Project Short name exists in Project term  
           if (term_ProjectName.Terms.Where(t => t.Name.ToLower() == projectShortName.ToLower()).Count() > 0)  
           {  
             //Get the Project Term for the Project Short Name  
             Term oterm = term_ProjectName.Terms.FirstOrDefault(t => t.Name.ToLower() == projectShortName.ToLower());  
             SPField metadatafld = spList.Fields["ProjectName"];  
             //id;#Term Name|Guid of term  
             //Get the ID  
             string taxonomyID;  
             SPList taxonomyHiddenList = spSite.RootWeb.Lists.Cast<SPList>().FirstOrDefault(l => l.Title.ToString() == "TaxonomyHiddenList");  
             taxonomyID = taxonomyHiddenList.Items.Cast<SPListItem>().FirstOrDefault(i => i["IdForTerm"].ToString() == oterm.Id.ToString()).ID.ToString();  
             metadatafld.DefaultValue = taxonomyID + ";#" + oterm.Name + "|" + oterm.Id;  
             metadatafld.Update();  
             spList.Update();  
           }  
         }  

No comments:

Post a Comment