1

In a custom controller, when I try to use drupal_set_message() in a custom Module Controller it works only if I put :

drupal_set_message('Test error', 'error');

return array(
   '#type' => 'markup',
   '#markup' => "Welcome",
);

=> the message is shown via {{ page.highlighted }}

If I put :

drupal_set_message('Test error', 'error');

return array(
   '#type' => 'page',
   '#markup' => "Welcome",
);

It doesn't work... I need to put a type page to be able to inject custom variables. Does anybody can help me to understand how it works ? I try to read the docs and a Drupal 8 book but I really don't understand how that works.

Thanks !

5

You might want to try

return array(
  '#theme' => 'ctr',
  '#myvar' => 'myvalue',
);

And then define a hook_theme.

/**
 * Implements hook_theme().
 */
function ctr_theme($existing, $type, $theme, $path) {
  $variables = array(
    'ctr' => array(
      'template' => 'cntr',
      'variables' => array(
        'myvar' => 'defaultvalue',
      ),
    ),
  );
  return $variables;
}
  • 1
    I've never seen that before does it definitely work? The documented approach is to use #NAMEOFVAR, so in this case '#myvar' => 'myvalue' at the same array level as '#theme' – Clive Jan 7 '17 at 17:48
  • You're right, #myvar needs to be at the same level as #theme. I updated my answer. – Wim Mostrey Jan 7 '17 at 17:54
1

it doesn't seems to work => forgot to mention that the twig template is handled by a custom theme and it's outside of my custom module.

So in my controller :

I have put something like :

return array(
    '#theme' => 'mytheme',
    '#myvar' => 'myvalue',
);

And in mymodule.module :

function mymodule_theme($existing, $type, $theme, $path) {

    $variables = [
        'template' => 'mycustompage',
        'variables' => [ 'myvar' => 'defaultvalue']
    ];
}

=> I got this error :

Template "modules/ctr/templates/cntr.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/ctr/templates/cntr.html.twig" in the Drupal theme registry.). (* in my case ctr = mymodule, cntr = mytheme)

  • Clear Drupal cache drush cr – Kevin Jan 9 '17 at 16:10
  • I updated my answer with the new information. After making the adjustments, be sure to clear cache. – Wim Mostrey Jan 9 '17 at 18:02
  • yes indeed I forgot to put drush cr -l mystagginenv Many thanks !! – injetkilo Jan 12 '17 at 13:43

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.