Publishing Page Layout DateTimeField formatting

I wanted to have my DateTimeField show up with a different format than the 'short date' value that it defaults to. Unfortunately you can't just add a date format string to a field property to make this work. I've seen a few alternative ways to do this involving extending the DateTimeField control. But I didn't like those options and felt the way I finally figured out was a little nicer (in my opinion).

Here's what I did:

1. Add a code behind page to your page layout and wire it up. If you don't know how to do this watch this short video by Andrew Connell. The 2nd part has to do with Page Layouts but you do the exact same thing as he does in the first part with the master page.

2. Add an 2 EditModePanels to your page layout like so:

<PublishingWebControls:EditModePanel runat="server" ID="DateEditModePanel">
  <SharePointWebControls:DateTimeField ID="ArticleDateControl" runat="server" FieldName="NewsArticleDate" />
</PublishingWebControls:EditModePanel>
<PublishingWebControls:EditModePanel runat="server" ID="DateDisplayModePanel" PageDisplayMode="Display">
  <asp:Label runat="server" ID="lblFormatDate" />
</PublishingWebControls:EditModePanel>

3. Add the following control references to your code-behind class

protected Label lblFormatDate;
protected DateTimeField ArticleDateControl;

4. Add the following code in your code behind page:

protected override void OnLoad(EventArgs e)
{
if (this.ArticleDateControl != null)
{
string dateString = "";
try
{
dateString = Convert.ToDateTime(this.ArticleDateControl.ItemFieldValue).ToString("MMMM d, yyyy");
}
catch
{
dateString = "";
}
lblFormatDate.Text = dateString;
}
}


5. Do the dance of joy.

Comments

Anonymous said…
It might be better to avoid adding code-behind to a page layout. If a user edits the page layout with SharePoint Designer, then the page will crash. I found this solution instead: http://panvega.wordpress.com/2009/03/16/masterpagepagelayout-format-date-field/

Regards,
Tomas
Paul said…
That is a valid point. We have a strict no SharePoint Designer policy on modifying our Master Pages. But I'm going to check out your solution, Thanks for your suggestion!
Phi said…
Remember base.OnLoad() or else your publshing commands will not be available in the ribbon!

Popular posts from this blog

ERROR: Failed to create feature receiver...

Renaming a Sharepoint 2007 / WSS 3.0 Server