-1

I'm getting this error:

LogicException: The controller must return a response (Object(Drupal\Core\Render\Markup) given). in Symfony\Component\HttpKernel\HttpKernel->handleRaw() (line 157 of C:\xampp\htdocs\drupal-8.1.10\vendor\symfony\http-kernel\HttpKernel.php).

Below is the code that I'm trying to execute:

<?php
/**
 * @file
 * Contains \Drupal\my_module\Controller\DefaultController.
 */

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Default controller for the my_module module.
 */
class DefaultController extends ControllerBase {

  public function my_module(\Drupal\user\UserInterface $user = NULL) {
    $name = $mail = $roles = $picture = "";

    if (!$user->getUsername() && $user->getUsername()) {
      $name = $user->getUsername();
    }

    if (!$user->getEmail() && $user->getEmail())->get('my_module_user_email_display_status')) {
      $mail = $user->getEmail();
    }

    foreach ($user->getRoles() as $value) {
      $roles = $value;
    }

    $user_data = [
      'name' => \Drupal\Component\Utility\SafeMarkup::checkPlain($name),
      'mail' => \Drupal\Component\Utility\SafeMarkup::checkPlain($mail),
      'roles' => \Drupal\Component\Utility\SafeMarkup::checkPlain($roles),
    ];

    $my_module_template_build = array(
      '#theme' => 'my_module_template',
      '#details' => $user_data,
    );

    $my_module_template = drupal_render($my_module_template_build);

    return $my_module_template;
  }
}
1
  • Btw. You should use \Drupal::service('renderer')->renderRoot() instead of deprecated drupal_render().
    – kenorb
    Commented Aug 4, 2017 at 21:55

3 Answers 3

2

You can return $my_module_template_build, e.g.:

$my_module_template = \Drupal::service('renderer')->renderRoot($my_module_template_build);
1

You've to return a response using Response Object, instead of returning rendered HTML as string, check code snippet provided here.

3
  • Yes, I tried that but that didn't solved my issue, this gave me a fatal: Fatal error: Class 'Drupal\my_module\Controller\Response' not found in C:\xampp\htdocs\drupal-8.1.10\modules\my_module\src\Controller\DefaultController.php on line 49 Commented Sep 29, 2016 at 6:07
  • Seems like instead of returning string or response object, you've to return simple array, check this ref.
    – Yogesh
    Commented Sep 29, 2016 at 6:19
  • You are missing the use statement for the response class.
    – Berdir
    Commented Sep 29, 2016 at 8:10
1

Try

return array(
  '#markup' => $my_module_template
);

Instead of

return $my_module_template;

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.