0

I've got a view page, which is pulling together quite a few content types. All of these content types have a field called field_image, however some are not required and/or are missing.

I basically need to grab the first (latest - sorting by author date in my view settings) row, check if there's a field_image, if there is, we can just return that field, if not, repeat.

I thought about a few different ways of doing this, and I thought that I'd make it a Twig command for ease. My issue is that I can't seem to get the single field I'm looking for.

My Twig function is currently:

public function get_first_instance($field, $rows) {
  foreach($rows[0]['#rows'] as $row) {
    dump($row['#row']);
    exit;
  }
}

I'm running the Twig command from my views-view--my-content-type--page.html.twig template, passing a string, and rows.

I can see that the field_image is located in _entity > #fields > field_image, I'm just not sure how to reference this, or what function to use to load the entity?

Thanks for any help in advance.

0

Solved it, makes sense now!

public function get_first_instance($field, $rows) {

  foreach($rows[0]['#rows'] as $row) {
    $entity = $row['#row']->_entity;

    if($entity->hasField($field)) {
      $value = $entity->get($field)->getValue();

      if(! empty($value)) {
        return $value;
      }
    }
  }

  return dump('Field not found: '.$field);
}
| improve this answer | |

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.