Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
proper way to access a field value in drupal
<?php
// Check if the value of a field is equal to the $pathway variable.
$pathway = 'category 1';
try {
if (arg(0) == 'node' && is_numeric(arg(1))) {
$wrapper = entity_metadata_wrapper('node', arg(1));
if ($wrapper->field_FIELD_NAME->value()->name != $pathway) {
return TRUE;
}
}
} catch (Exception $e) {
drupal_set_message($e->getMessage(), 'error');
}
?>
@barraponto

This comment has been minimized.

Copy link

@barraponto barraponto commented Mar 22, 2014

What about:

return !empty($wrapper->field_FIELD_NAME) && ($wrapper->field_FIELD_NAME->value()->name != $pathway);
@Greg-Boggs

This comment has been minimized.

Copy link
Owner Author

@Greg-Boggs Greg-Boggs commented Jul 10, 2014

That's a great question. In general, I avoid putting logic statements in returns because it can be confusing to understand what's being returned.

In a simple example, checking empty on every line of code works. In an example where you have 5 or 10 fields to access, the code gets messy and it's easier to make a mistake and leave out a !empty check. With a try catch, it's almost impossible to forget to catch your error. I've also found many, many examples online leave out the proper !empty check

<?php
$name = !empty($wrapper->field_name) && ($wrapper->field_name->value()->name;
$date = !empty($wrapper->field_date) && ($wrapper->field_date->value()->name;
$image = !empty($wrapper->field_image) && ($wrapper->field_image->value()->name;
$link = !empty($wrapper->field_link) && ($wrapper->field_link->value()->name;
$tag = !empty($wrapper->field_tags) && ($wrapper->field_tags->value()->name;

// Meanwhile, my code would read

try {
  $name = $wrapper->field_name->value()->name;
  $date = $wrapper->field_date->value()->name;
  $image = $wrapper->field_image->value()->name;
  $link = $wrapper->field_link->value()->name;
  $tag = $wrapper->field_tags->value()->name;
} catch (Exception $e) {
    drupal_set_message($e->getMessage(), 'error');
}
?>
@randomletters

This comment has been minimized.

Copy link

@randomletters randomletters commented Aug 20, 2014

The down side to this approach is that once an error occurs, none of the other subsequent lines will be run. Therefore, if "field_name" does not exist but "field_date" does, none of the variables you intended to set will be set.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment