I have a content type "Slide" that I use for a carousel in a view as a block. One of the field of the slide I have added is "country filter" that I intent to use as a filter for geo localisation. I use GeoIP2 for this.

My intent was to use a THEME_preprocess_SOMETHING() to alter the view and remove some of the slides that are not on the right country filter. For example some slides could be allowed to be shown only to user located in France. If the user is not located in France, I would remove those slides.

I tried to do this in a THEME_preprocess_view_view_fields() but I can seem to find a way to remove completely the slide. So I guessed I was not on the right hook.

Does anyone knows which hook I should use to do that?

1 Answer 1


I haven't found a way to do it in a THEME.theme file but I found a way to do it in a MODULE.MODULE file. The magic hook is MODULE_views_post_execute:

function feature_carrousel_views_post_execute(\Drupal\views\ViewExecutable $viewExecutable){
  /** @var \Drupal\views\Entity\View $view */
  $view = $viewExecutable->storage;
  if($view->id() == 'carrousel'){
    /** @var \Drupal\views\ResultRow $row */
    foreach($viewExecutable->result as $key => $row){
      $nid = $row->nid;
      /** @var \Drupal\node\NodeInterface $node */
      $node = \Drupal\node\Entity\Node::load($nid);
      if($node) {
        $country_filter = $node->get("field_country_filter")->getValue();
        $country_filter_tid = (reset($country_filter))['target_id'];
        /** @var \Drupal\taxonomy\Entity\Term $term */
        $term = \Drupal\taxonomy\Entity\Term::load($country_filter_tid);
        $name = $term->getName();
        $countryCode = getUserCountry();

        if(strtolower($name) != 'all' && strtolower($name) != strtolower($countryCode)) {
          $viewExecutable->result = array_values($viewExecutable->result);



  • In case of views in Drupal 8 one thing has changed which makes hook views not working as expected. It's views cache that is enabled by default. If you edit your view and expand "Advanced" tab you will see "Caching" option. Its default state is set to "Tag based", change it to none and you will be able to change more then you could expect with views hooks.
    – David
    Commented Apr 6, 2017 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.