Make Plugins Execute Based on Resource Context

Enable or disable plugins in the Manager based on Resource Context


In the previous article, we looked at how to enable or disable front-end plugins based on current context. In this one, we'll look at doing something similar in the MODX Manager.


MODX logo

The Problem

Imagine that, on a multi-context site, you have a plugin tied to a Manager event like OnDocFormPrerender. The plugin adds fields to the Create/Edit Resource panel, but you only want those fields added to resources in a particular context.


The Solution

To restrict the plugin to resources in a single context, you just need to check the context_key field of the current resource. Suppose you have a French language context with the key fr. You want the plugin to execute only in that context This code at the top of your plugin would do it:

if (isset($resource)) {
    if ($resource->get('context_key') !== 'fr') {
       return;
    }
}

Now, the plugin will return without doing anything if the resource is not in the fr context.

As we saw in the previous article, we can use the strict inequality operator (!==), because the context_key field will always be a string.

If we wanted the plugin to execute in all front-end contexts *except* the fr context, we'd do this:

if (isset($resource)) {
    if ($resource->get('context_key') === 'fr') {
       return;
    }
}

If the resource is in the fr context, the plugin will return without doing anything.


Multiple Contexts

Imagine that you have a number of contexts, but you want your plugin to execute only for resources in three of them: fr, de and en. Here's how to do that:

$allowedContexts = array('fr', 'de', 'en');
if (isset($resource)) {
    $key = $resource->get('context_key');
    if (! in_array($key, $allowedContexts)) {
        return;
    }
}

If you wanted the code to execute in all contexts *except* those three, you'd do this:

$disAllowedContexts = array('fr', 'de', 'en');
if (isset($resource)) {
    $key = $resource->get('context_key');
    if (in_array($key, $disAllowedContexts)) {
        return;
    }
}

Coming Up

In the next two articles, we'll see how to disable or enable plugins in the Manager based on other criteria.



Looking for high-quality, MODX-friendly hosting? As of May 2016, Bob's Guides is hosted at A2 hosting. (More information in the box below.)



Comments (0)


Please login to comment.

  (Login)