2

Is there a way to check, in a preprocess function, if the value of a field is empty?

I'm getting the following error.

Call to a member function isEmpty()

function iom_preprocess_block__twitterfeed(&$variables) {
  // Get the twitter_username field from node.
  $twitterUsername = \Drupal::routeMatch()
    ->getParameter('node')
    ->get('field_twitter_username')
    ->value; 

  if ($twitterUsername->isEmpty()) {
    dump("Empty");
  }
  else {
    dump("Not Empty");
  }
}
10

@vinhd proposition is correct, by the way you can also use the isEmpty() method from the field list interface. It can be more adapted for complex field types.

if ( $node->hasField('field_your_field') && !$node->get('field_your_field')->isEmpty() ) {
 //... do something
}
1
  • 1
    This is the correct answer: after get(..) you can call isEmpty right away. – ssibal Oct 16 '18 at 8:11
4

None of the other answers is fully correct, each one will only work in some cases. Before calling an object method, you have to check
- if the object exists,
- if the object is of the right type
- and if the object has that specific method/field.

The following code might look like a bit of an overkill, but it is the most bulletproof solution I've found so far. Everything I'm checking in there is based on a real word error I've had in my own projects:

function MYMODULE_preprocess_MYHOOK(&$variables) {

  $route = \Drupal::routeMatch();

  //special case node preview: has no node object, but a node_preview
  if ($route->getRouteName() == 'entity.node.preview') {
    $node = $route->getParameter('node_preview');
  }
  // this is the default case
  else {
    $node = $route->getParameter('node');
  }

  //$node can be either a node object (most of the times)
  //or an integer (on some admin routes)
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }

  // this if-statement is the important part that prevents the error messages
  if ($node instanceof \Drupal\node\NodeInterface && $node->hasField('field_MYFIELD')) {
    // no you can savely do whatever you want with field_MYFIELD
    $myVar = $node->get('field_MYFIELD')->value;
    $isEmpty = $node->get('field_MYFIELD')->isEmpty();
  }   
}
2

You can try code:

check has field:

$node = \Drupal::routeMatch()->getParameter('node');
if($node->hasField('field_twitter_username')){
  //todo code
}

check empty value

$field_value = $node->field_twitter_username->getValue()
if(!empty($field_value)){
  //todo code
}
3
  • Second option seems to caught an error Error: Call to a member function getValue() on string – clestcruz Oct 16 '18 at 6:45
  • can you check hasField that field does exist – vinhdv Oct 16 '18 at 6:51
  • @clestcruz it works great – vinhdv Oct 16 '18 at 6:52

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.