fix105
fix105

Reputation: 234

Sitecore: Find the value of a field for a selected Item

I'm trying to create some custom code inside my Sub Layout.

I have to build a newsletter, the newsletter can be composed on a number of article. An article can be composed by a title / Sub title / Header and image.

Can be, because the Sub title or the image are not mandatory. To avoid any empty space / missing image in the newsletter email, I would like to create a specific HTML based on the content.

If there is no image, don't show the Image control, if there is no Sub title, don't show the Sub Title control;

To do that, I'm using the following code which is not working :(

    Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/Home");

if(home != null && home.Fields != null)
{
string name = home.Fields["Image"].Name; -> Which Fields["Image"] returns null.
}

Is there another way to retreive the field of the selected article ? As my code is not working at all, I don't understand how to retreive the Field value of my selected Item.

Thank you.

Upvotes: 0

Views: 12027

Answers (2)

Bhawna Jain
Bhawna Jain

Reputation: 759

Here is one simple way :

Sitecore.Context.Item.Fields["You field name"]

Upvotes: 0

Jay S
Jay S

Reputation: 7994

In your example, home.Fields is just checking to make sure that the Fields collection exists. You aren't checking if there is a value in the Image field before trying to extract the name.

You probably need something like this:

if(home != null && home.Fields != null && home.Fields["Image"] != null)
{
   string name = home.Fields["Image"].Name;
}

Per your comments, it seems to be you are actually trying to pull the image field from the datasource of your component. If you want to conditionally check for the image field before doing something in that case, there are a lot of possible null exceptions that I would want to handle. The code should probably be something like:

var parent = ((Sitecore.Web.UI.WebControl)Parent);
if(parent != null){
   Item dataSourceItem = string.IsNullOrWhiteSpace(parent.DataSource) ? null : Sitecore.Context.Database.GetItem(parent.DataSource);

   if(dataSourceItem != null && dataSourceItem.Fields != null && dataSourceItem.Fields["Image"]!=null){
       string name=dataSourceItem.Fields["Image"].Name;
   }
}

Upvotes: 2

Related Questions