Moon
Moon

Reputation: 22565

Drupal 7 - is it okay to write php codes inside a template file?

I am learning Drupal 7 for my new project.

Here is what I want to do

  1. create a new content type called 'video'
  2. create a new module called 'video'
  3. make http://domain.com/video accessible.
  4. when a user access /video, then execute a query that queries video rows from video table (created by 'video' content type'), then display queries with a custom template.

I have learned how to do #1 ~ #3, but I am a little bit confused with #4.

let's assume that my custom template's filename is 'video.tpl.php'

in the video.tpl.php, do I write php functions to query video rows?

I don't think that is a good practice. Instead, I want to write a module and call a function in the module when the video.tpl.php is loaded.

How do I do it?

Upvotes: 0

Views: 769

Answers (3)

Berdir
Berdir

Reputation: 6891

For 4, you first need to create a module, implement hook_menu(), define a menu item for 'videos' with a page callback. If you don't know how to do that, there are likely already a lot of questions about that). Inside the page callback, you need to do 3 things.

  1. Load the nids, something like

    $nids = db_query("SELECT nid FROM {node} WHERE type = 'video' ORDER BY created DESC")->fetchCol();

  2. Load the nodes.

    $nodes = node_load_multiple($nids);

  3. Build them.

    return node_view_multiple($nodes);

But again, you should only do this if you want to learn the API. Views will all of this do for you, you just need to click it together.

Upvotes: 2

dzogchen
dzogchen

Reputation: 383

Views is definitely the way to go. you could write a module, but it would be like re-inventing the wheel. Learn Views and you will use it again and again.... tutorials:

a views tutorial

Another views tutorial

Upvotes: 1

bluefoot
bluefoot

Reputation: 10580

You should use views

Upvotes: 1

Related Questions