December 13, 2024

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

[code language=”csharp”]

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

[/code]

to

[code language=”csharp”]

public partial class SublayoutDatasourceSample : SublayoutBase

[/code]

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,

[code language=”xml”]

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

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

[/code]

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

[code language=”csharp”]

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

[/code]

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!

Leave a Reply

Your email address will not be published. Required fields are marked *