1

Is there a way to access the fields in paragraph in views-view-unformatted.twig.
I want to perform checking on field of paragraph before print the row
something like this

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {% if paragraph_field is not null %}
     <div {{ row.attributes.addClass(row_classes) }}>
        {{ row.content }}
     </div>
  {% endif %}
{% endfor %}

1 Answer 1

1

I don't think you can get the value of field from paragraph field inside views-view-unformatted.twig all you can get is the target_id of referenced paragraph using view.result[key]._entity:

I suggest to use template_preprocess_views_view_unformatted like the following:

function YOURTHEME_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
  if ($view->id() === 'YOUR_VIEW_ID') {
    $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
    foreach ($rows as $id => $row) {
      /** @var \Drupal\node\Entity\Node $node */
      $node = $view->result[$id]->_entity;
      // Get paragraph field.
      // Change field_paragraph by your filed ref to paragraph.
      if ($node->hasField('field_paragraph')) {
        $paragraph_ref_id = $node->field_paragraph->getValue()[0]['target_id'] ?? NULL;
        if ($paragraph_ref_id) {
          /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph_entity */
          $paragraph_entity = $paragraph_storage->load($paragraph_ref_id);
          // Get the value of your field.
          // Change field_paragraph_text by your field.
          // And set another variable to use in twig.
          $variables['rows'][$id]['should_display_row'] = ($paragraph_entity->field_paragraph_text->value !== NULL) ? TRUE : FALSE;
        }
      }
    }
  }
}

Now in your views-view-unformatted.twig you can check on row.should_display_row like the following:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {% if row.should_display_row %}
    <div{{ row.attributes.addClass(row_classes) }}>
      {{- row.content -}}
    </div>
  {% endif %}
{% endfor %}
2
  • Great answer. But I did use hook_views_query_alter to add condition for paragraph field.
    – Saf
    Commented Jan 17, 2020 at 16:31
  • How did you do that, I'm interested in the reverse, accessing view fields inside a paragraphs template
    – Shawn W
    Commented Nov 11, 2022 at 2:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.