3

Up until now, I have found it most convenient and easy to place PHP code into my node by placing it in the node body and enabling the PHP filter. However, I have been informed that this is incorrect and unsafe.

Furthermore, I also know that it would be incorrect to place PHP code in node.tpl.php.

Could someone please tell me where the correct place to place PHP code for a node would be?

5

One of two places, hook_node_view() or hook_preprocess_node(). They can both be used in a module file, but only the latter will work in your theme's template.php file.

hook_node_view() example:

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'my_node_type') {
    $args = array(':nid' => $node->nid);
    $my_value = db_query('SELECT my_field FROM {my_table} WHERE nid = :nid', $args)->fetchField();

    $node->content['my_value'] = array(
      '#markup' => 'My value is: ' . $my_value, 
      '#weight' => 10 // Controls the display order of this piece of content
    );
  }
}

hook_preprocess_node() example:

function MYMODULE_preprocess_node(&$vars) {
  $vars['content']['my_additional_field'] = array(
    '#markup' => $additional_field, 
    '#weight' => 10, 
    '#theme' => 'mymodule_my_additional_field',
  );
}
| improve this answer | |
  • thanks. But if for example I wish Node A to display some data from the database, in which file should I put that code? – chlong Apr 19 '12 at 16:50
  • Are you familiar with writing custom modules? Or would you rather do this in your theme? – Clive Apr 19 '12 at 16:52
  • I am very familiar with writing custom modules. I just can't (conceptually) complete the link between how my module will affect the display of a node body content. (ie. If I have your first hook_node_view in my custom module, would I have to create another file to actually put the PHP code that would grab the database content?) – chlong Apr 19 '12 at 16:53
  • Gotcha. In your node.tpl.php file you'll probably have the line print render($content);, which prints out all of the node content. In the preprocess/node_view function you can query the database and add to the $node->content or $vars['content'] render array. I'll update the first method in the answer with an example – Clive Apr 19 '12 at 16:55
  • I got it working. But I am having trouble returning a list of values from the query. I currently have $query = db_query('SELECT OFFICE_ID FROM OFFICE LIMIT 0, 10')->fetchField();, however this only returns me the first field. I have tried 'fetchObject' and 'fetchCol' but both only a string 'Array', which gets printed out as in your code. Do you know how I can display the entire list that is returned by the query? – chlong Apr 19 '12 at 20:03

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.