1

I have created a field in a Basic Page with the label of User Name and the field name of field_user_name.

How can I get it's value using PHP?

5
  • 1
    Whats the value of $nid in that context?
    – Clive
    Jun 24, 2013 at 10:41
  • I do want to if fix it should be get automatically because when ever any user will create a new node than it should get automatically Jun 24, 2013 at 10:44
  • 1
    No Drupal won't automatically inject code for you - if you want to load a node, you need to provide the nid to node_load() in some way
    – Clive
    Jun 24, 2013 at 11:00
  • You won't see data with print(). Use print_r($field_value);. Or better debug($field_value);, or dpm($field_value);
    – milkovsky
    Jun 24, 2013 at 18:10
  • If you have another question, then you should post it as a question rather than edit an existing one. It'll get no visibility and won't help other people :)
    – Chapabu
    Jun 27, 2013 at 8:20

2 Answers 2

10

The easiest non Entity API way of doing it is to use field_get_items():

// Assuming you have the node object and assuming it is a single value
// field or you just want the first value of a multi value field.
$username_value = '';
if ($items = field_get_items('node', $node, 'field_user_name')) {
  $username_value = $items[0]['value'];
}
7

Not sure what you mean by global PHP, but here goes anyway.

I'd use the entity_metadata_wrapper(). For further reference, there's the handbook page here, but you're looking at something like the following:

// Assuming the NID if your Basic Page node is 123
$node = node_load(123);
$wrapper = entity_metadata_wrapper('node', $node);

$field_value = $wrapper->FIELD_NAME->value();

You'd need the Entity API installed, but if you're running D7 then it's a pretty safe bet that something will have required it in the past as a dependency.

2
  • How can I get node id ? Jun 24, 2013 at 9:56
  • 3
    @MohitGoyal It's the ID of the node you're interested in loading. How you get it depends completely on the context your code is in
    – Clive
    Jun 24, 2013 at 9:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.