|Number of votes:||4|
Adding custom logic to your publishing step
With EPiServer there are great, easy ways to add validation to your content. You can easily add DataAnnotations like [Required] to your properties to individually validate them.There is also the IValidator interface you can implement to handle validation of the Save event. See the documentation for more info - http://world.episerver.com/Documentation/Items/Developers-Guide/EPiServer-CMS/7/Validation/Validation/
Content Events to the Rescue!
Now the interesting bit
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.
The ContentEventArgs e 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.
Please login to comment.