Jump to main content Jump to doc navigation

Writing Plugins

Other versions: 3.x — Other languages: EN RU — Found a problem? Please edit this page or report an issue.

What is a Plugin?

Plugins are similar to Snippets in that they are bits of PHP code that have access to the MODX API. The big difference, however, is in when the code executes. You put Snippets inside of a page or inside a template and they run when the page is viewed, whereas Plugins are set to execute during certain system events, e.g. saving a Chunk, or emptying the cache. So when a given event "fires", any Plugin "listening" for that event is executed. Once the Plugin's code has executed, control returns to the point after the spot where the System Event was triggered.

Other CMSs Every CMS uses some concept of "plugin", but the exact nomenclature may differ. In WordPress, for example, plugins are "hooked" to events called "actions" or "filters".

Since they execute during various events, Plugins aren't limited to front-end processing. Many events are triggered by events that take place only within the MODX Manager. There is a list of MODX System Events here.

Any closing PHP tag ?> will be stripped from your plugin code when it is saved. It's unnecessary (and unwanted) because the plugin code will end up inside other PHP code when executed.

The Event Model

MODX invokes System Events across its code processes to allow you to modify core functionality without hacking the core. These System Events can have any number of Plugins attached to them, and will execute each Plugin in rank according to its priority (lowest numbers first).

Handling an Event

In your Plugin, how you handle the output depends on the System Event you are in. For some system events, you return a value from the Plugin. For others, you access the output by reference and modify it.

If you need to know which event triggered your plugin (say, for a plugin that listens to more than one event), you can access the Event's name like so:

$eventName = $modx->event->name;

The code for a Plugin listening to more than one event looks like this:

$eventName = $modx->event->name;
switch($eventName) {
    case 'OnWebPageInit':
        /* do something */
        break;
    case 'OnWebPagePrerender':
        /* do something else */
        break;
}

Plugin Examples

Plugins can be used for a variety of different applications, below are a couple of examples:

Message the User:

Description: Send a custom message to the user as they create/edit a page... a custom header. System Events: OnDocFormPrerender

$modx->event->output('Hi there user!');

Custom Validation

Description: Do some custom validation on saving a page resource System Events: OnBeforeDocFormSave

// Do some logical stuff.... if validation failed:
$modx->event->output('Something did not validate!');
return "This goes to the logs";

The trick here is that what you want to message the user has to be passed to the $modx->event->output() function; any text you want to write to the logs can simply be returned by the plugin. If you pass validation, simply return null.

No HTML Allowed The output you set in $modx->event->output() must not contain any HTML! Use plain text only! This is because the message is passed to the user via a Javascript modal window.

Return value must be a string. If your return value will be a number, concatenate it with an empty string.

Word Filter

Description: Filter words from a document before it's displayed on the web System Events: OnWebPagePrerender

$words = array("snippet", "template"); // words to filter
$output = &$modx->resource->_output; // get a reference to the output
$output = str_replace($words,"<b>[filtered]</b>",$output);

Page-Not-Found Redirector:

Description: Redirects a user to selected document and sends a message System Events: OnPageNotFound System Settings:

  • pnf.page: Error Resource ID
  • pnf.mailto: Mail To Address
  • pnf.mailfrom: Mail From Address
if ($modx->event->name == 'OnPageNotFound') {
     $errorPage = $modx->getOption('pnf.page');
     if (empty($errorPage)) {
         $modx->sendErrorPage();
     } else {
         $mailto = $modx->getOption('pnf.mailto');
         if (!empty($mailto)) {
            // send a message to a local account
            $resourceId = $modx->resource->get('id');
            $subject = 'Page not found';
            $body = 'Someone tried to access document id '.$resourceId;
            $modx->getService('mail', 'mail.modPHPMailer');
            $modx->mail->set(modMail::MAIL_BODY, $body);
            $modx->mail->set(modMail::MAIL_FROM, $modx->getOption('pnf.mailfrom'));
            $modx->mail->set(modMail::MAIL_FROM_NAME, 'MODX');
            $modx->mail->set(modMail::MAIL_SENDER, 'MODX');
            $modx->mail->set(modMail::MAIL_SUBJECT, $subject);
            $modx->mail->address('to',$mailto);
            $modx->mail->setHTML(true);
            $modx->mail->send();
         }
         $url = $this->makeUrl($scriptProperties['page']);
         $modx->sendRedirect($url, 1);
         exit;
    }
}

See Also

  1. System Events
  2. OnBeforeCacheUpdate
  3. OnBeforeChunkFormDelete
  4. OnBeforeChunkFormSave
  5. OnBeforeDocFormDelete
  6. OnBeforeDocFormSave
  7. OnBeforeManagerLogout
  8. OnBeforeSaveWebPageCache
  9. OnBeforeWebLogout
  10. OnCacheUpdate
  11. OnChunkFormDelete
  12. OnChunkFormPrerender
  13. OnChunkFormRender
  14. OnChunkFormSave
  15. OnDocFormDelete
  16. OnDocFormPrerender
  17. OnDocFormRender
  18. OnDocFormSave
  19. OnDocPublished
  20. OnDocUnPublished
  21. OnLoadWebPageCache
  22. OnManagerLogin
  23. OnManagerLogout
  24. OnSiteRefresh
  25. OnUserChangePassword
  26. OnWebLogin
  27. OnWebLogout
  28. OnWebPagePrerender
  29. OnManagerPageBeforeRender
  30. OnTemplateVarBeforeSave
  31. OnTemplateVarSave
  32. OnTemplateVarBeforeRemove
  33. OnTemplateVarRemove
  34. OnBeforeEmptyTrash
  35. OnBeforeManagerLogin
  36. OnBeforeManagerPageInit
  37. OnBeforePluginFormDelete
  38. OnBeforePluginFormSave
  39. OnBeforeSnipFormDelete
  40. OnBeforeSnipFormSave
  41. OnBeforeTempFormDelete
  42. OnBeforeTempFormSave
  43. OnBeforeTVFormDelete
  44. OnBeforeTVFormSave
  45. OnBeforeUserActivate
  46. OnBeforeUserFormDelete
  47. OnBeforeUserFormSave
  48. OnBeforeWebLogin
  49. OnCategoryBeforeRemove
  50. OnCategoryBeforeSave
  51. OnCategoryRemove
  52. OnCategorySave
  53. OnChunkBeforeRemove
  54. OnChunkBeforeSave
  55. OnChunkRemove
  56. OnChunkSave
  57. OnContextBeforeRemove
  58. OnContextBeforeSave
  59. OnContextFormPrerender
  60. OnContextFormRender
  61. OnContextRemove
  62. OnContextSave
  63. OnEmptyTrash
  64. OnFileManagerUpload
  65. OnHandleRequest
  66. OnInitCulture
  67. OnLoadWebDocument
  68. OnManagerAuthentication
  69. OnManagerLoginFormPrerender
  70. OnManagerLoginFormRender
  71. OnManagerPageAfterRender
  72. OnManagerPageInit
  73. OnPageNotFound
  74. OnPageUnauthorized
  75. OnParseDocument
  76. OnPluginBeforeRemove
  77. OnPluginBeforeSave
  78. OnPluginEventRemove
  79. OnPluginFormDelete
  80. OnPluginFormPrerender
  81. OnPluginFormRender
  82. OnPluginFormSave
  83. OnPluginRemove
  84. OnPluginSave
  85. OnPropertySetBeforeRemove
  86. OnPropertySetBeforeSave
  87. OnPropertySetRemove
  88. OnPropertySetSave
  89. OnResourceGroupBeforeRemove
  90. OnResourceGroupBeforeSave
  91. OnResourceGroupRemove
  92. OnResourceGroupSave
  93. OnRichTextBrowserInit
  94. OnRichTextEditorInit
  95. OnRichTextEditorRegister
  96. OnSiteSettingsRender
  97. OnUserActivate
  98. OnUserBeforeRemove
  99. OnUserBeforeSave
  100. OnUserFormDelete
  101. OnUserFormSave
  102. OnUserNotFound
  103. OnUserRemove
  104. OnUserSave
  105. OnWebAuthentication
  106. OnWebPageComplete
  107. OnWebPageInit