You could do this by overriding the ExecuteRendering
processor in the renderRendering
pipeline, and running the validation in there. If the PageMode.IsPreview
is true, then run the validator and if the validator succeeds, then you can run run execute the rendering.
The following should give you a good start, but is not tested:
public class ExecuteRendererWithValidation : Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecureRenderer
{
public override void Process(RenderRenderingArgs args)
{
if (Sitecore.Context.PageMode.IsPreview)
{
// If we are in preview mode and the item validates
// then render the component. Otherwise, hide it from the
// editor
if (ValidateItem(args.PageContext.Item)){
base.Process(args);
}
}
else
{
base.Process(args);
}
}
private bool ValidateItem(Item item) {
var validator = ValidatorManager.BuildValidator(item, Sitecore.Context.Item);
validator.Validate(new ValidatorOptions(false));
return validator.IsValid;
}
}
You would then need to patch this processor in, instead of the default processor:
<?xml version="1.0"?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<pipelines>
<mvc.renderRendering>
<processor type="Sitecore.Mvc.Pipelines.Response.RenderRendering.ExecuteRenderer, Sitecore.Mvc">
<patch:attribute name="type">MyNamespace.ExecuteRendererWithValidation, MyAssembly</patch:attribute>
</processor>
</mvc.renderRendering>
</pipelines>
</sitecore>
</configuration>
That should then hide the rendering in preview mode if the datasource item does not validate.