简体   繁体   中英

Sitecore 8 throwing null exception when Datasource item does not exist

I am facing the below problem and can't find out how to get around to it.

  1. I have a rendering and its datasource is pointing to an item in the tree.
  2. I publish the rendering but I don't publish the referenced item.
  3. While viewing the page I get an error. [attached is the screen shot of the error i am getting]

在此处输入图片说明

I am using glass mapper.

Thanks in advance for your help.

The best solution would be to tap into the mvc.getRenderer pipeline and validate the datasource actually exists, otherwise fallback gracefully.

There are a number of solutions already proposed for this and is a known "issue", although it is not a Glass specific issue:

All these solutions check if the datasource item exists, in normal mode the error is swallowed but in Page Editor mode a warning is displayed to the editors so show the fact that datasource needs to be set in cases where none has been selected.

It was also raised as an issue in Glass Mapper with a similar solution.

To elaborate jammykam's answer, you can do something like the code below which I have found in this blog

Config Patch:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <mvc .getrenderer="">
        <processor patch:instead="processor[@type='Sitecore.Mvc.Pipelines.Response.GetRenderer.GetViewRenderer, Sitecore.Mvc']" type="Namespace.To.Sitecore.Pipelines.Response.GetRenderer.GetViewRendererWithItemValidation, Library">
        </processor>
      </mvc>
    </pipelines>
  </sitecore>
</configuration>

Code:

public class GetViewRendererWithItemValidation : GetViewRenderer
{        `
    protected override Renderer GetRenderer(Rendering rendering, GetRendererArgs args)
    {           
        var viewRenderer = base.GetRenderer(rendering, args) as ViewRenderer;
        if (viewRenderer == null)
            return null;

        // Ignore item check when in page editor
        // Also this will break if the item for the datasource has been deleted without removing the link.
        if (Context.PageMode.IsPageEditor || Context.PageMode.IsPageEditorEditing)
            return viewRenderer;

        // Override renderer to null when there is an unpublished item refererenced by underlying view
        return viewRenderer.Rendering.Item != null && viewRenderer.Rendering.RenderingItem.InnerItem != null
            ? viewRenderer
            : null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM