Page Editor Experience – Fetch the Datasource in code of a Presentation Component

Dear Sitecore Family,

In the previous 2 posts, we just saw how to configure a Datasource in a  Presentation Component and Adding a Component from Page Editor.

The previous posts are not of any specific use, if we don’t see how do we retrieve it in code and how do we display it!

So lets just have a look at it.

Well the first thing, as we all know, its always good to use the DRY Rule of Software Engineering!

Step-1: So instead of writing a big piece of code to fetch the Datasource, its good to use the Sitecore Module Sublayout Parameter Helper by John West.

Step-2: We change the inheritance of the Sublayout Component – we change it from System.Web.UI.UserControl to Sublayoutbase as follows:

Change


public partial class SublayoutDatasourceSample : System.Web.UI.UserControl

to


public partial class SublayoutDatasourceSample : SublayoutBase

Step-3: After the above step, when we build our solution and check for DataSourceItem in our Sublayout Page_Load function code, its available — this is a property visible from the SublayoutBase class!

DataSourceItem-Sublayout-Base

So we just apply a couple of required validations and next is assign it as the Item for the various fields we have created.

Say, I add a couple of FieldRenderers in the ascx code,


<sc:FieldRenderer runat="server" ID="Header" FieldName="Heading" />

<sc:FieldRenderer runat="server" ID="Content" FieldName="Content" />

And using the DataSourceItem property, I assign the Item to these two controls as follows:


public partial class SublayoutDatasourceSample : SublayoutBase
{
protected void Page_Load(object sender, EventArgs e)
{
Header.Item = DataSourceItem;
Content.Item = DataSourceItem;
}
}

And the work is done!

So we see, how easy it gets when we are aware of the things that are already available and how to use them.

Thank you John West for this Awesome Module, it definitely saves us from a lot of repetition of code in various Sitecore Projects!

Happy Sitecoring!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s