Challenge #3 – The First Draft

19 November 2018 Solved Php Intermediate

A real-world use case for send­ing email noti­fic­a­tions when a new entry draft is cre­ated using a Craft mod­ule and an event hand­ler. It requires set­ting up a mod­ule and writ­ing some PHP code, so pull up your sleeves and dust off your IDE.


The chal­lenge is to cre­ate a mod­ule that listens for the EntryRevisions::EVENT_AFTER_SAVE_DRAFT event. Whenev­er the event is fired, provided that the draft is new, the mod­ule should send a noti­fic­a­tion email to the sys­tem email address with the sub­ject First Draft” and the fol­low­ing message:

A new entry draft “{title}” has been cre­ated by “{user­name}”: {cpUrl}

Where {title} is replaced by the title of the entry draft, {username} is replaced by the user­name of the user that cre­ated the draft and {cpUrl} is the URL to edit the entry in the con­trol panel.

For bonus points, if the envir­on­ment vari­able FIRST_DRAFT_EMAIL_TEMPLATE is set then the mod­ule should use the rendered tem­plate (as defined by the the envir­on­ment vari­able) as the email’s HTML body, provid­ing the 3 vari­ables above as tem­plate variables.


The mod­ule must be a single, self-con­tained file that sends an email noti­fic­a­tion as described above whenev­er a draft is cre­ated, if and only if the draft is new (not a revi­sion of an exist­ing draft). It should not rely on any plu­gins and the code will be eval­u­ated based on the fol­low­ing cri­ter­ia in order of priority:

  1. Use of Craft components 
  2. Read­ab­il­ity
  3. Brev­ity

There­fore the code should use nat­ive Craft com­pon­ents wherever pos­sible. It should be read­able and easy to under­stand, con­cise and non-repetative.


Every install­a­tion of Craft cre­ated using the Craft pro­ject as doc­u­mented in the install­a­tion instruc­tions comes with a modules/Module.php file. You can use this file as a start­ing point or read the guide on how to build a mod­ule and cre­ate your own.

For an in-depth explan­a­tion of mod­ules you can read the art­icle Enhan­cing a Craft CMS 3 Web­site with a Cus­tom Mod­ule.


Submitted Solutions

  • Spenser Hannon