0

I'm looking into building a custom Context Provider, specifically to provide "groups of the current user". I'm building this for another plugin, a Condition plugin, whose purpose is to filter things (e.g. Blocks) based on the current user's group roles.

I'm aware that the following issues and patches exist, which does get me somewhere:

However, both patches only ever deal with a single group, i.e. the context provider only picks out essentially the first group a user belongs to, and the condition plugin is provided one group for evaluation. What I'd like to do is have the the context provider provide multiple groups (all the groups the user belongs to) and have the condition plugin accept multiple groups.

But how do I provide and consume an array of values as context value?

Most examples for context provider and plugins consuming context values only operate on single values. I've not seen examples on how to provide an array (of groups in this case).

1 Answer 1

3

Let's start with this:

Most examples for context provider and plugins consuming context values only operate on single values.

While that's true, recognize that the "single value" being provided is an object, not a primitive type. In the case of the Group context provider, that "single value" is an Entity object of type 'group'. The entity itself contains all the usual data - id, label, description, created date, author, base fields, etc. So it's wrong to think of it as one number only.

To provide an array of values, you need to return an object that represents a data structure instead of an Entity. The core Typed Data API defines a variety of datatypes, of which the Map type is probably the best for your purpose. Map holds a collection of values, similar to a familiar associative array in PHP.

So the outline of the solution is to create your own context provider by copying the existing Group context provider, modify your copy so that instead of creating an Entity context definition you create a Map context definition, then add the values you want to provide to your Map.

If you need more functionality, you can create your own datatype (I recommend subclassing Map for this) and provide an object of that datatype instead of an Entity or a Map.

You can find a short example of how to write your own Context Provider here: https://www.drupal.org/docs/contributed-modules/rules-essentials/for-developers/providing-global-context-variables

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.