Hi,

I have cck. I want to get hold of the node id of the current node inside a php code field (body field with input type set to php). How do I do that? And is there any list of attributes that a node object has?

Cheers, Toby

Comments

modul’s picture

Hi tobbe,

$node is a widely available object.

$node->nid will give you the node id ("nid" in drupalese) of the current node.

And this thingy

<?php
print_r($node);
?>

will give you all the attributes.

I just hope everything shows up properly in this forum...

Ludo

tobbe_s’s picture

Thanks for your quick answer, ludo.

However, I have tried several variations on print_r($node) and print $node->id, but I don't get any output whatsoever from these. I have also tried specifiying global $node at the start of the php field. And I have tried placing print_r($node) in node.tpl.php, with the same, meagre result. Any clues on this? Is there any strange drupal-setting that needs to be disabled for this to work (I'm new to Drupal, but not to php)?

Cheers

modul’s picture

- Could you send me an exact sample of the code which is not working, and of the place / file where you applied it?
- By the way, what exactly do you mean by "php field" ??
- Are you sure you have set the "Input format" of the file where you want to apply your code to PHP? If you really don't see any output, my feeling is there is something wrong there. Have you tried with adding some plain "echo something" code around your nid lines, just to make sure there is (or is no) PHP output?

L.

tobbe_s’s picture

oops, posted before finished typing

tobbe_s’s picture

Here's the code:

<?php
global $node;
print_r($node);
echo "Hello";
?>
aha

This code was entered into the body field of a node, and the input type of the field was set to PHP code. The output after the node is saved is just

Helloaha

And there is no "extra" output in the source of the page. So at least php is evaluated on the field. I.e.
print_r($_GET)
prints the expected output, so it seems that the node object is not loaded properly into the $node variable.
The server runs php5.1.

nevets’s picture

If you want to work with the current node, where current node means you are looking at a page with the output from a single node and the unaliased path is of the form "node/{nid}" the following will help

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
  $node = node_load(arg(1));
  // Do something with $node
  // If all you need is the nid you can use
  // $nid = arg(1)
}
?>

Note this code is only triggered when viewing the node by it's self so when looking a list of nodes it does not do anything.

tobbe_s’s picture

Thanks nevets, that worked like a charm!

modul’s picture

Darn, I forgot: the "$node->nid" code does not work in the node's body PHP, but only in node-yourcontenttype.tpl.php . Sorry for my stupid mistake. Oh well, now you have 2 approaches :-)

Ludo

ralarsen’s picture

I tried this:

if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
  $node = node_load(arg(1));
  // Do something with $node
  echo $node;
  // If all you need is the nid you can use
  // $nid = arg(1)
}

But the page returns:

recoverable fatal error: Object of class stdClass could not be converted to string in /usr/home/n624725/public_html/drupal/includes/common.inc(1547) : eval()'d code on line 7.

WorldFallz’s picture

use print_r($node)

===
"Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime." - Lao Tzu
"God helps those who help themselves." - Ben Franklin
"Search is your best friend." - Worldfallz

binhcan’s picture

Thanks so much nevets. You saved my life.

I've been struggling whole day trying to figure out how to get the $node variable to work in a PHP filtered custom block for my Drupal site Chinese Furniture. Finally I found yours and it's working.

Big kisses.

princemanjee’s picture

I have been bashing my head against the computer for DAYS trying to figure out why it wasn't working and when I did I couldn't figure out how to solve it until i stumbled onto this post... THANK YOU SO MUCH. If you ever decide to leave the serenity of Wisconsin and venture to Chicago please let me know I owe you a beer... or ten!

One small Question... Is there a way or a string of Code I SHOULD be using instead of what I have here that would perform the same task but with more efficiency/less code etc. New to Drupal and PHP (Not from a programming back ground). My concern is If I fill up my site with redundant code and inefficient processes it is just going to cause the site to slow in the event there is a significant amount of traffic. Trimming the fat from the code is a lot more frugal than buying an insanely expensive server.

Using Drupal 6.13 and the modules trying to bridge the gap for here are Rules and Node Relativity.

Thanks in advance for any suggestions you might have!

CODE:
--------

function rules_action_mail_to_user2($user, $settings) { // Cloned Script See Above For Original Syn.

// Load Node ID
  $node = node_load(arg(1));
  $nid = arg(1);

// Load Load Parent Node
      $result = db_query('SELECT parent_nid FROM {relativity} WHERE nid = %d', $node->nid);
      $object = db_fetch_object($result);
      $parent_node = $object->parent_nid;
      $parentm = node_load($node->parent_node); 
// Load Parent Node Author
      $result = db_query('SELECT uid FROM {node} WHERE nid = %d', $object->parent_nid);
      $object = db_fetch_object($result);
      $parent_node = $object->uid;
      $parentm = node_load($node->uid); 
// Load Parent Node Author Email
      $result = db_query('SELECT mail FROM {users} WHERE uid = %d', $object->uid);
      $object = db_fetch_object($result);
      $parent_node = $object->mail;
      $mailerz = $object->mail;

// Insert Parent Author Email Address


  $to = $object->mail;  // instead of   $to = isset($settings['to']) ? str_replace(array("\r", "\n"), '', $settings['to']) : $object->mail;

// END OF LOCAL MODIFICATONS - PRM
  $from = ($settings['from']) ? str_replace(array("\r", "\n"), '', $settings['from']) : NULL;

  $message = drupal_mail('rules', 'rules_action_mail', $to, language_default(), $settings, $from);
  if ($message['result']) {
    watchdog('rules', 'Successfully sent email to %recipient', array('%recipient' => $to));
  }

}
nevets’s picture

The code as written does not make much sense, you are setting variables that are never used and you seem to have "extra" data base calls. What are you trying to do?

wicketywick’s picture

what a relief, this problem has been itching me real bad. Thanks nevets.

betoth’s picture

For those who may be using content_profile module, I found that I needed the uid to set some option values for a cck option widget. The function call passes very little useful input to your custom php function, so I am grabbing the uid from the URL. I did not use the global $user because I wanted the admins to be able to see the proper dropdowns and selected values. Please let me know if you have a better strategy.

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

function getUID() {
  $purl = curPageURL();
  $purl = substr($purl, stripos($purl,'/user/')+6 );
  if( stripos($purl,'/') > 0 ) {
    return substr($purl,0,stripos($purl,'/') );
  } else {
    return $purl;
  }
}
nevets’s picture

How about arg(1)?

betoth’s picture

Yes arg(1) would suffice. I am not sure how much the path moves around, so I can do it with the following function. Perhaps this is clearer as to what arg I am after.

function get_uid_by_arg() {
  $args = arg();
  for( $i = 0; $i < sizeof($args); $i++ ) {
    if( $args[$i] == 'user' ) return $args[$i+1];
  } 
nevets’s picture

Unaliased path is user/[uid] so I just use arg(1). If I want to make sure it is a user page I check arg(0) to see that it is 'user'.