Alter a view. Edit view result programmatically | Drupal 8

Alter a view. Edit view result programmatically

Submitted by editor on Fri, 09/30/2016 - 11:16
Question

How to Edit a view result programmatically ?

Example : Change title

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_myviewname') {

    // Set the view title.
    $view->setTitle('New title');
    $result = $view->result;
    // Set the ro title
    foreach ($result as $i => $row) {
      $view->_entity->set('title', 'New titile for row');
      // set / anter field value
      $row->_entity->set('field_name', "new value");    
    }
  }
}

Change a field value/render (Example):
function hook_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];

  $field = $variables['field'];
  $row = $variables['row'];
  if ($view->storage->id() == 'view_name' &&
  $view->current_display == 'view_display_id' &&
  $field->field == 'field_name') {
    $variables['output'] = 'News output';
    // Example of inline styling
    $value = $field->getValue($row);
    $markup = [
      '#type' => 'inline_template',
      '#template' => '{{ yourvar }} {{ yourhtml | raw }}',
      '#context' => [
        'yourvar' => $value,
        'yourhtml' => '<span style="color:red;">Your HTML</span>',
      ],
    ];
    $variables['output'] = $markup;
  }
}

 

CAUTION : Following example is not working for Drupal 9 :

function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'view_myviewname') {
    $result = $view->result;
    foreach ($result as $i => $row) {

      $view->result[$i]->field_field_myfieldtext[0]['rendered']['#markup'] = "The new text";
    }
  }
}

Comments

hess (not verified)

Tue, 10/18/2016 - 13:31

How can i edit a view? I mean where should i add this program? I am really new to D8. trying to learn it.

Ruchira (not verified)

Mon, 10/09/2017 - 15:49

If view having empty result then no debug working in views_pre_render(&$view). So waht was another solution to handle no result message programmatically. 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.