Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop validation error item from being published

We are using Sitecore 7.2 and have implemented the 'Required' field validator for number of fields.

However, the user can still save or create an item with validation error.

I know that we can stop this validation errored items from being published using Work Flow.

We do not want to implement any workflow, therefore can someone please suggest how to stop validation errored item from being able to published?

like image 223
Nil Pun Avatar asked Sep 15 '25 23:09

Nil Pun


1 Answers

You can create your own validation class like this (the one below only check for validation bar errors):

public void ValidateItem(object sender, EventArgs args)
{
    ItemProcessingEventArgs theArgs = (ItemProcessingEventArgs) args;
    Item currentItem = theArgs.Context.PublishHelper.GetSourceItem(theArgs.Context.ItemId);
    if ((currentItem != null) && (currentItem.Paths.IsContentItem))
    {
        if (!IsItemValid(currentItem))
        {
            theArgs.Cancel = true;
        }
    }
}

private static bool IsItemValid(Item item)
{
    item.Fields.ReadAll();
    ValidatorCollection validators = ValidatorManager.GetFieldsValidators(
        ValidatorsMode.ValidatorBar, item.Fields.Select(f => new FieldDescriptor(item, f.Name)), item.Database);
    var options = new ValidatorOptions(true);
    ValidatorManager.Validate(validators, options);
    foreach (BaseValidator validator in validators)
    {
        if (validator.Result != ValidatorResult.Valid)
        {
            return false;
        }
    }
    return true;
}

and add event handler to publish:itemProcessing event:

<event name="publish:itemProcessing" help="Receives an argument of type ItemProcessingEventArgs (namespace: Sitecore.Publishing.Pipelines.PublishItem)">
    <handler type="My.Assembly.Namespace.ValidateBeforePublish, My.Assembly" method="ValidateItem"/>
</event>
like image 83
Marek Musielak Avatar answered Sep 17 '25 20:09

Marek Musielak