0

In Drupal 8, I created a view containing a Custom Text field. I want to alter/change its content for each row I get after running some code. I tried implementing hook_views_pre_render() and template_preprocess_views_view_fields(), but I wasn't able to access this field.

I also would like to learn when this nothing field is added to the view output, and after which hook.

  • 1
    For whatever reason seems like "nothing" can't be accessed. You could add some other field again and use that instead, or you could create a custom variable in hook_preprocess_views_view_fields and then print the variable in your views-view-fields--[view-name].html.twig file. – No Sssweat Aug 9 '18 at 22:38
0

I tried to do this with a lot of (Views) hooks, but with no luck because of the (nothing) field seems not part of the entity data.

Finally I managed to alter that value by implementing theme template_preprocess_views_view_fields() in my module.

/**
 * Implements template_preprocess_views_view_fields().
 */
function MODULENAME_preprocess_views_view_field(&$vars) {
  // Print all available fields.
  foreach ($vars['view']->field as $key => $field) {
    // We will print the field name.
    print $key . '<HR>';
  }
  exit;

  // To access current row entity.
  $entity = $vars['row']->_entity;
  $entity_id = $entity->id();

  // To access entities from relationship.
  $entities = $vars['row']->_relationship_entities;

  // When you find your field key use this code below.
  if(isset($vars['view']) && ($vars['view']->id() == 'VIEW_MACHINE_NAME') && ($vars['view']->current_display == 'DISPLAY_MACHINE_NAME')) {
    if (isset($vars['view']->field) && (count($vars['view']->field) > 0)) {
      // if ($vars['field']->field == 'YOUR_FIELD_NAME')
      if ($vars['field']->field == 'nothing') {
        $vars['output'] =  [
          '#markup' => 'WRITE_NEW_VALUE_HERE_OR_CHANGE_THIS_RENDERABLE_ARRAY_TO_RENDERABLE_IMAGE_OR_WHATEVERY_YOU_WANT',
        ];
      }
    }
  }
}

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.