I created a custom module mycustom. I have a view for which I am trying to alter the field data. For instance, an image field and I am trying to alter the uri. I don't want to use rewrite rule because I want this field to be altered for every view, and even for displays not controlled by Views.

At first I tried adding to my module

mycustom_preprocess_field(&$variables, $hook)

But this function is never called.

Then I tried

mycustom_preprocess_views_view_field(&$variables)

The function is called, but the $variables is unruly. A print_r on $variables['fields'] crashes the browser.

So I can't readily figure out how to manipulate the data. Reading about the Field API is sort of like walking blindfolded in a big city trying to find a certain store on a certain road, without anyone around to help. I can't figure out how to return the field name.

I found something online that led me to the following to get the field output:

$variables['field']->advancedRender($variables['row']);

That works. And shockingly a google search on "Drupal 8 advancedRender" does not even return an API page. I came across the function under core/modules/views/src/plugins/views/field/FieldHandlerInterface.php but I don't see other functions that would return a field name.

So in general, I am not sure how to go about implementing a hook to alter the field.

If anyone can show some example code to alter a field that would be immensely appreciated!

Thanks

Comments

Devline’s picture

Using your mycustom_preprocess_views_view_field(&$variables) you may try to :

1) get the field name : $variables['field']->realField
2) get the field value : $variables['field']->getValue($variables['row'])
3) get the field classes in the view : $variables['field']->elementClasses()

Then set your custom output for the field.

I hope this will help.

harchew’s picture

Is it possible to overwrite existing field value and how can it be done?

samgao’s picture

I came across the same issue, and this is what I did. I need to target that field first in hook_preprocess_views_view_field, then use $variables['output'] = [Your custom value];

Hope this helps solve your issue.

Tunprog’s picture

Works like a charm.
@Devline thank you.

stephenplatz’s picture

@Devline this is helpful, thanks, but I'd love to see some documentation somewhere for this, I guess I'll keep looking.

ravimalviya2000’s picture

We have updated value any view field with below example.

for example :

hook_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  if ($view->storage->id() == 'viewname' &&
  $view->current_display == 'pageid' &&
  $field->field == 'title') {
    //$variables['output'] = 'News output';
  }

  if ($view->storage->id() == 'viewname' &&
  $view->current_display == 'pageid' &&
  $field->field == 'nid') {
    //$variables['output'] = '3';
  }
}