In one of our projects we had a requirement to target the content of a SharePoint Publishing HTML field to an audience. The content should only be displayed to users that are member of an audience. It was very easy to create this and below you can find the steps to create this yourself:
- Create a new class that inherits from Microsoft.SharePoint.Publishing.WebControls.RichHtmlField
- Add a public property that holds the name of the audience
- Override the Onload and implement this as below:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SPSite site = SPControl.GetContextSite(Context);
ServerContext context = ServerContext.GetContext(site);
AudienceManager audienceManager = new AudienceManager(context);
Audience audience = audienceManager.GetAudience(this.Audience);
SPUser user = SPControl.GetContextWeb(Context).CurrentUser;
if (audience == null ||
!audience.IsMember(user.LoginName))
{
this.Visible = false;
}
}
- Add a new Publishing HTML field to the Pages library called “MyTargetedField”.
- Edit one of your Page Layouts and add a registration for your assembly :
<%@ Register Tagprefix="EogWebControls" Namespace="TST.WebParts.AudienceRichHtmlField"
Assembly="TST.WebParts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=503edd7b21a430b3" %>
- Add the new webpart to your page layout and set the Audience property to “MyAudience” :
<EogWebControls:AudienceRichHtmlField id="PageContent4" Audience="MyAudience" FieldName="MyTargetedField" runat="server"/>
- Create an audience “MyAudience” with some rules and compile it.
- Create a page based on this page layout and test if the content you entered in the “MyTargetedField” only shows up for members of the “MyAudience” audience.
As you can see, it is very easy to do with just a few lines of code.
Erwin, thanks for preparing this!