Using Control Adapter to Set Default Values for Publishing Pages
Developers, who use customized page layouts bound with custom content type, have probably realized that if your custom content type is not the default content type of Pages library, you will not get default values populated when you create a new page. One way to work around this is to create feature, which sets your customized content type to be the default (1st content type) in Pages library. However, it does not work for the rest of the page layouts in that same library.
Here is another workaround to consider. Create a control adapter, which will populate default values to any of the publishing page in Pages library.
{
protected override void OnLoad(EventArgs e)
{
var bfc = Control as BaseFieldControl;
var context = SPContext.Current;
if (bfc != null && context != null)
{
var item = context.ListItem;
if (item != null)
{
if (bfc.Field != null && !Page.IsPostBack)
{
var defaultValue = bfc.Field.DefaultValueTyped;
if (defaultValue != null)
{
if (bfc.ItemFieldValue == null)
bfc.ItemFieldValue = defaultValue;
if (bfc.Value == null)
bfc.Value = defaultValue;
}
}
}
}
base.OnLoad(e);
}
}
When using adapter you need to create .browser file for the web application’s App_Browsers directory
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="Microsoft.SharePoint.WebControls.BaseFieldControl"
adapterType="..BaseFieldControlAdapter, ..., Ver..., Cul..., Pub..." />
</controlAdapters>
</browser>
</browsers>
As a bonus, if you override Render method, you can use it to mark Required field on the page in edit mode by changeing the css class of that control and then customize it as you wish.
{
var bfc = Control as BaseFieldControl;
if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit ||
bfc == null || bfc.Field == null || !bfc.Field.Required)
{
base.Render(writer);
return;
}
using (var sw = new StringWriter())
{
using (var tw = new HtmlTextWriter(sw))
{
base.Render(tw);
}
sw.GetStringBuilder()
.Replace("ms-formfieldcontainer", "ms-formfieldcontainer req");
writer.Write(sw.ToString());
}
}
Snippets above demonstrate just how to use control adapter to do this. You still need to check if current page is in edit mode and that it’s a new page (otherwise it will always display the default values, not the saved ones).
***********************************************
Jerry Seinfeld: Why not? We’re neighbors. What’s mine is yours.
Cosmo Kramer: [leaning against the door-frame and looking around in wonder] Really?
***********************************************
Popularity: 6% [?]
[...] While ago I posted something very similar to this. Here [...]
Dude, you have a bug in the adapter. The condition should be
if (SPContext.Current.FormContext.FormMode != SPControlMode.Edit ||
bfc == null || bfc.Field == null || !bfc.Field.Required)
Alhis, you got that right.
I will update the code.
Thanks for collaboration.