0

I have a custom block and I'm able to update its content using #pre_render if I'm using basic text.

However I'm unable to print database query results using the same way. Below is my code.

function _maintenance_prerender(array $build) { 
$build['content']['#markup'] = myDatabaseQuery();
return $build;
}

function myDatabaseQuery() {
  $query = \Drupal::database()->select('menu_link_content_data', 'm');
  $query->condition('m.title', 'Visit');
  $results = $query->execute();
}

Is there a special way to print database query results on a custom block?

2

To be able to exploit your result, you should fetch your result with one of the function of the Statement class.

If you use the function fetchAll() for example, you will have an array of objects with all your result.

$results = $query->execute()->fetchAll();

You can do a function to create your markup with that array.

You can also not use a function from Statement and do a foreach directly on the result generate by the execute() function to create your markup

$results = $query->execute();

foreach($results as $res) {
    $markup .= "<tr><td>$res->field_1</td><td>$res->field_2</td></tr>";
}

If you want see how is design your array, you can install the module kint (from the devel module) and display your result with

ksm($results);

Additionnally, to work, your query should have the list of fields it should select.

$query->fields('m', ['field_1', 'field_2']);

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.