Drupal 7: Get Data from Database and Create a Table with Theme_table

The code is as below:

/**
* display the data.
*/
function display_data($form, &$form_state) {
//Use Database API to retrieve records.
$query = db_select(‘info_manager’, ‘n’)
->fields(‘n’, array(‘id’, ‘first_name’, ‘last_name’, ’email’))
->orderBy(‘id’, ‘DESC’); //Most recent first.
$result = $query->execute();

//Iterate over the resultset and format them.
$header = array(‘ID’, ‘First Name’, ‘Last Name’, ‘Email’);
$rows = array();
foreach ($result as $row){
$rows[] = array($row->id,
$row->fist_name,
$row->last_name,
$row->email,
);
}

if (empty($rows)) { //No content in the last week.
$page_array[‘info_manager_arguments’] = array(
//Title serves as page subtitle
‘#title’ => t(‘All posts from the last week’),
‘#markup’ => t(‘No posts available.’),
);
return $page_array;
}
else {
$page_array[‘info_manager_arguments’] = array(
‘#header’ => $header,
‘#rows’ => $rows,
//Theme function includes theme hook suggestion.
‘#theme’ => ‘table__info_manager’,
);
return $page_array;
}
}

helpful links:

Default theme implementations
https://api.drupal.org/api/drupal/modules!system!theme.api.php/group/themeable/7

Drupal for Beginners: How to Create a Table Using theme_table()
http://zgadzaj.com/drupal-for-beginners-how-to-create-a-table-using-themetable

Leave a Reply

Your email address will not be published. Required fields are marked *