Skip to main content

I had a couple of instances where I needed to check if an object field existed.  Initially I used propertyExists. However, when running Solr, it tripped on this command.  So some other function was required.  And in steps hasField().  It is a good idea to validate the existence before using it to avoid any unexpected error.

 

Code:

$entity->hasField('fieldName');

 

Drupal API hasField() function determines if Drupal entity has a field with a given name or not. It returns a boolean “TRUE” if the given name is found or “FALSE” otherwise.  By way of example, the following code using hasField() method:

/**
 * Get the value of an Entity field.
 * First by confirming that the field exists in the current entity.
 * Second, check the current paragraph has a value.
 * 
 * @param Object $entity
 * @param String $fieldName
 *
 * @return Array
*/
function get_field_values($entity, $fieldName) {
  $values = [];
  if ($entity->hasField($fieldName)) {
    $field = $entity->get($fieldName);
    if (!$field->isEmpty()) {
      $fieldValue = $field->getValue();
      $values = load_field_values($fieldValue);
    }
  }
  return $values;
}

 

Whilst, it not required in this example, I do call another function and in case I get a request for it... here it is:

/**
 * Retrieve the field values.
 *
 * @param Array $values
 *
 * @return Array
 */
function load_field_values($values) {
  $results = [];
  foreach ($values as $value) {
    $results[] = $value['target_id'];
  }
  return $results;
}

 

The get_field_values function, I have used in paragraphs and media with great success.