While both these are a simple and effective, one question I am hearing from developers and customers is how can I set up custom business rules for validating who can publish a content item?
Content Events to the Rescue!
The easiest way here is to use the built in IContentEvents to determine when an event like Content Publishing is triggered. This applies globally to all sites so I would consider writing this code into an InitializationModule like in the example below. IContentEvents exposes a number of events, because here we’re interested in before content is published, we will use PublishingContent. All the events have a pre / post event so there is also a PublishedContent event.
Let’s say the customer use case is they wanted someone other than the content Creator to be able to publish. For example, I can publish your work but not my own.
This isn’t standard functionality and fits well into our scenario.
Here’s an example solution to solving this. Here I am testing whether the content to be published implements IChangeTrackable which gives us access to the CreatedBy property. If its the same person as the current user then we want to cancel publishing.
e.CancelReason = "Unable to publish content created by the same user. Please mark as 'Ready to Publish' and have another user publish";
The ContentEventArgse gives us the content item which we can test against. It also provides us with properties to cancel the action and provide a message to the editor. Like the validation options mentioned at the start, this hooks in nicely to the editor so they get error messages like this.
Polishing it up
So now that the validation code is in place I’d tidy a few things up to make this production ready.
To start off I would separate out the concern of the validation into a validator class. In this example there is only 1 validation but potentially there could be several. Also importantly this means we can unit test the validator class functionality. My completed PublishingValidator looks like this.
My InitializationModule will now use this class through the ServiceLocator. I registered IPublishingValidator in my dependency resolver initialization. Finally I will add the LocalizationService to make the error message localized to the editor’s language. Here is the final code for the PublishingContent event handler.