Problem/Motivation

In D7 we could set an active context during runtime in a custom module using context_set_context()
This does not seem possible in the D9/10 version?

Proposed resolution

Create public methods in the ContextManager service to allow for setting and unsetting an active context.

setActiveContexts($context_names);
unsetActiveContexts($context_names);
isActiveContext($name);

ex:

// Set context_1 and context_2 to be active, if they exist.
\Drupal::service('context.manager')->setActiveContexts(['context_1', 'context_2']);
CommentFileSizeAuthor
#3 context-set_context-3263552-3.patch702 bytesloze

Issue fork context-3263552

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

loze created an issue. See original summary.

loze’s picture

Title: How to programmatically set a context » How to programmatically set an active context
loze’s picture

Category: Support request » Feature request
Status: Active » Needs review
StatusFileSize
new702 bytes

I combed through the code and couldn't find a way to do this. so I added a method to the contextManager.

It appears to work as expected. Now if I call the following:
\Drupal::service('context.manager')->setActiveContext('CONTEXT_NAME');
from my custom module, the context is set (provided it exists and is enabled)

loze’s picture

Version: 8.x-4.x-dev » 5.x-dev
loze’s picture

Issue summary: View changes

loze’s picture

Changed setActiveContext($name) to setActiveContexts($context_names);
Added unsetActiveContexts($context_names);
Added isActiveContext($name);

loze’s picture

Title: How to programmatically set an active context » Allow setting/unsetting the active contexts programmatically
Issue summary: View changes
admirlju’s picture

The changes worked for me. I'm just wondering if maybe there should be some tests made for this code because it's not used by any other code and someone might potentially delete it in the future. So I'll leave it as Needs Review for now, just so people can debate this a bit.

agile-mark-l made their first commit to this issue’s fork.

markman4897’s picture

I have submitted a commit that removes an unnecessary newline in the ContextManager.php file.
Additionally, I have written basic kernel tests to validate the new functionality implemented in this issue.

loze’s picture

Thanks for the test @agile-mark-l this looks good.

Anonymous’s picture

Status: Needs review » Reviewed & tested by the community

I've taken a look into this feature requests and it seems that MR is ready to be merged, tests pass and feature has been implemented as requested. Marking this issue as RTBC.