Thursday, April 26, 2012

Error while adding Site columns (fields) to list content types

Recently, I had a situation where I need to add site columns (available in root web) to a content type reference in a particular list under a particular web.

I wrote the code below 
 
var field = web.Site.RootWeb.AvailableFields[new Guid("<<FieldID>>")];
foreach (SPContentType cType in web.Lists["ListName"].ContentTypes)
{
    cType.Fields.Add(field);
    cType.Update();
}

but it was not working as expected and throwing the below exception

"This functionality is unavailable for field collections not associated with a list."

After some research, I came to know that the field needs to be added as a SPFieldLink and not as SPField itself since the field already exists in the root web. The below modified code is working fine for me.

var field = web.Site.RootWeb.AvailableFields[new Guid("<<FieldID>>")];
foreach (SPContentType cType in web.Lists["ListName"].ContentTypes)
{
    SPFieldLink fieldLink = new SPFieldLink(field);
    cType.FieldLinks.Add(fieldLink);
    cType.Update();
}

Hopefully this helps some one or may be myself in the future when I struggle with the same issue.

Thanks
Senthil S

Monday, April 2, 2012

Java script error when trying to change Page Layout

Recently, I faced a weird issue with SharePoint publishing pages and changing the layout of the page. I was able to add a new publishing page with different layouts in a pages library. But when I try to change the page layout of an existing page, I got a java script error in cui.debug.js. Just like the one below, I was not even be able to get the drop down with different page layouts to change


To fix this issue I had to debug the java script (CUI.debug.js) file in IE 8 or greater using the Developer tools. Once the exception occurred in the java script, traced the function calls using the "Call Stack" option and found a variable "$v_0.PopulationXML" and inspected the XML in VS and found the malformed XML.



After some research, I came to know that there was a orphaned page layout in the "Master Pages and Page Layouts" gallery. I was testing something else with page layout and content type relationships and left it there. But I removed the content type associated with the page layout.

After I deleted the particular page layout from the gallery, everything started to work fine.

Thanks
Senthil S