Programatically rewrite view fields in Drupal 8

Problem: I had the need to re-write some view fields programatically

Solution: 

  1. first use template_preprocess_views_view_fields hook

    ex:- yourtheme_preprocess_views_view_fields(&$variables)

  2. get the any field 
    $view = $variables['view'];
    $row = $variables['row'];
    // You can get the field value for the field this way even if the field is hidden (excluded from display)
    $field_value = $view->style_plugin->getField($row->index, 'your_field_machine_name');
  3. Now assign a value to the field
    // To assign html markup
    $variables['fields']['your_field_machine_name']->content = \Drupal\Core\Render\Markup::create($html_string_here);
    //Raw value
    $variables['fields']['your_field_machine_name']->content = $raw_value

Hope this saves you some time

Tags