Score:0

Add a variable for each row to use in views-view-unformatted template

my flag

We are making a new website from an old Drupal 7 project. For each item within a view, I need to check if a file exists in order to enable or disable a link. In Drupal 7 we used file_exists() within the PHP template but we can't do that anymore with Twig.

I have opted for using the template_preprocess_views_view_unformatted(&$variables) function but I don't succeed in setting the variable properly.

function bootstrap5_preprocess_views_view_unformatted(&$variables) {
    $variables['#cache']['max-age'] = 0;

    $id_view = $variables['view']->id();
    // echo($id_view);
    switch ($id_view) {
        case 'recent_incidents_block':
            foreach ($variables['rows'] as $key => &$value) {
                
                // $value['content']['#row']->file_exists= "test";
                $variables['rows'][$key]['file_exists'] = "test";
            }
        break;
    }
}

Then in the view template:

{% for row in rows %}
  {% set file_exists = row.file_exists.value %}

But nothing gets printed with {{file_exists}}

ru flag
A string like `"test"` is a primitive scalar datatype, it doesn't have any sub-properties or keys like `.value`. But whatever you are trying here, you are almost certainly doing it weird, Drupal's/Twig's `{{ content }}` render array is empty-aware, Twig has empty-operators for logic and you can drill entity references within Twig by appending `.entity` on the ER field.
sonfd avatar
in flag
Is this a drupal managed file? Can you just add a field to your view in the UI?
No Sssweat avatar
ua flag
Try `file_exits = row.file_exists` no value.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.