5

I have several contexts defined for my site. In hook_form_alter I need to find out which of them are active. I am trying to use context_active_contexts, but that is only showing 2 of the (at least) 3 that are active. i.e. I have contexts A, B and C. C has a block reaction and the block is visible. My code only outputs A and B. If I disable C, the block disappears from the output, giving me some confidence that it really is context C that is responsible for it. Why can I not see A, B and C in the output?

function MyModule_get_current_location_contexts() {
  $contexts = context_active_contexts();

  $locations = array();
  foreach ($contexts as $context) {
    $locations[$context->name] = $context;
  }

  return $locations;
}

function MyModule_form_alter(&$form, &$form_state, $form_id){
  dsm('Contexts (form):');
  if ($form_id == 'MyForm') {
    $contexts = MyModule_get_current_location_contexts();

    foreach ($contexts as $context) {
      dsm($context->name);
    }

    dsm($form);
  }
}

function MyModule_node_view($node, $view_mode, $langcode) {
  dsm('Contexts (entity):');
  $contexts = MyModule_get_current_location_contexts();

  foreach ($contexts as $context) {
    dsm($context->name);
  }
}
2

The context name is the array key, not it's ->name field. See my answer here on how to programmatically check if a context is active.

No need for foreach loop on $contexts on the 2nd and 3rd functions. Instead of loopoing on $contexts and printing for each context it's name field, you should simply print the array keys:

print_r (array_keys($contexts));
0

I believe the cause is that your form alter function is firing before the node conditions are met, so the context isn't active until a little later on in the Drupal loading.

One solution is to attach an #after_build callback in your form alter, to can check the active context properly.

function example_form_alter(&$form, &$form_state, $form_id) {
  $form['#after_build'][] = 'example_form_alter_node_after_build';
}

function example_form_alter_node_after_build($form, &$form_state) {
  // Check active contexts here
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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