Let's says if Sitecore Item item
has a field Created by
with type Link Types:Droptree
I want to print the name of item which is saved in the field Created by
. The following line <sc:Text Field="Created by" runat="server"/>
will print the ItemId. What is the efficient way to display the name of this item.
I know that I can get the item from the database and then print its name as:
<asp:Label runat="server" ID="lblItemName"></asp:Label>
In Codebehind:
if (!Page.IsPostBack)
{
Item currentItem = Sitecore.Context.Item;
Item relatedItem = Sitecore.Context.Database.GetItem(currentItem["Created by"]);
lblItemName.Text = relatedItem.Name;
}
I don't think it is possible to render the name of an item with <sc:Text />
as it is a field renderer.
So you will have to do like you did:
var currentItem = Sitecore.Context.Item;
// Alternative way to get the linked item
var createdByField = (ReferenceField) currentItem.Fields["Created by"];
var createdByItem = createdByField.TargetItem;
var createdByItemName = createdByItem.Name;
lblItemName.Text = createdByItemName;
If you want to render a field from the linked item (createdByItem
) instead of the current context item, you can do it like this:
<sc:Text runat="server" Field="Headline" ID="scRelatedItem" />
and int the code behind you set the Item property to the item you want to read the Headline field from:
scRelatedItem.Item = createdByItem;
Doing it this way will also make the field editable by editors through the Page Editor (called Experience Editor in Sitecore 8).