Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By simone960 on
I have created a simple module trying to list out some fields from the database. However, I couldn't figure out how to expose a field for filtering, e.g title, just like how we easily do it via Views module. Any idea? Here is part of the code:
function myModule_list() {
// Table header
$header = array(
array('data' => 'Nid', 'field' => 'nid', 'sort' => 'desc'),
array('data' => 'Title', 'field' => 'title'),
);
// Query
$query = db_select('node', 'n');
$query->fields('n', array('nid', 'title'));
$query->condition('type', 'news');
$query->extend('PagerDefault')
->limit(10);
$query->extend('TableSort')
->orderByHeader($header);
$nodes = $query->execute();
// Table rows
$rows = array();
foreach ($nodes as $node) {
$rows[] = array(
'data' => array($node->nid, $node->title),
);
}
// Output
$output['content'] = array(
'#theme' => 'table',
'#caption' => '<h2>News</h2>',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('available soon..'),
'#weight' => 1,
);
// Pager
$output['pager'] = array(
'#theme' => 'pager',
'#weight' => 2,
);
return $output;
}
Comments
Why not use the views module?
Why not use the views module?
I'm just learning Form API
I'm just learning Form API and module development, thinking to explore more on the coding part instead of Views module.
My personal opinion is why re
My personal opinion is why re-invent the wheel?
You are right.. I think what
You are right.. I think what I need to learn is to code for Views, exposing my new data to views and work from there. Thanks for pointing out. ref: http://goo.gl/CKaAFP
Note from the code you have
Note from the code you have show you are dealing with content (nodes) and views already now how to work them.
Yep. the code I have shown
Yep. the code I have shown above indeed can be handled by views directly no doubt. My ultimate goal is actually to create a new entity, e.g Project, and creating some pages with some filters. But googling around I realized there's no need to code the filters, instead, expose it to the Views module and work from there. Correct me if I'm wrong.
Correct
You are right. Create an entity using something like this:
Of course you already need your table in the .install file and permissions, etc.
The lines
will make it visible to Views. Then you can just create a View and work from there on.
You question is a bit vague,
You question is a bit vague, so I am not sure what your goal is. But if you define custom entities "correctly" then views will know about them. Using the entity api (contrib module) is one way to do this.