Hi there,

I'd like to show/not show fields in a view depening on a condition (language)
I've found out I need to use the hook :
hook_views_pre_view
But can't find out how to show/hide fields using the hook.

Thx in advance!

Comments

dco’s picture

Use a views template suggestion and then hide unnacessary fields in it.

byenary’s picture

That could be a solution indeed, maybe its just easy'r then to create a sperate view for each language

xandeadx’s picture

for Views 3:

/**
 * Implements hook_views_pre_render().
 */
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME' && OTHER_CONDITIONS) {
    $view->field['FIELD_NAME']->options['exclude'] = TRUE;
  }
}
sunwukong’s picture

Subscribed

krystalcode’s picture

Nice one, would you know how you can do exclude the field but only for some of the results? For example:

/**
* Implements hook_views_pre_render().
*/
function MODULENAME_views_pre_render(&$view) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME' && OTHER_CONDITIONS) {
    foreach ($view->result as $item) {
      if (CONDITIONS) {
        $view->field['FIELD_NAME']->options['exclude'] = TRUE; // exclude field for only this result ???
      }
    }
  }
}
Sebastian Hagens’s picture

Good question.

I've made a solution with the views_conditional module (drupal.org/project/views_conditional).
Have you found a code-based solution (which is better in my case)?

ricobanga’s picture

Old thread, but as i found a simple solution :

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($whatever)
    $fields = $view->display_handler->get_option('fields');
    $fields["YOUR_FIELD"]['exclude'] = 1;
    $view->display_handler->override_option('fields', $fields);
  }
}
zoltanb’s picture

Nice, i could use the same logic in Drupal 8.

/**
 * Implements hook_views_pre_view().
 */
function MYMODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($WHATEVER) {
    $fields = $view->display_handler->getOption('fields');
    $fields['YOUR_FIELD']['exclude'] = TRUE;
    $view->display_handler->overrideOption('fields', $fields);
  }
}
suresh kumara’s picture

/**
* Implements hook_views_pre_render().
*/
function MODULENAME_views_pre_render(&$view) {
if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME' && OTHER_CONDITIONS) {
$view->field['FIELD_NAME']->options['exclude'] = TRUE;
}
}