Skip to content

Instantly share code, notes, and snippets.

@Greg-Boggs
Created October 23, 2013 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Greg-Boggs/7128108 to your computer and use it in GitHub Desktop.
Save Greg-Boggs/7128108 to your computer and use it in GitHub Desktop.
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
Copy link

What about:

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

@Greg-Boggs
Copy link
Author

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
Copy link

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