I need to switch view displays to filter referable content for specific roles.

/**
 * Implements hook_views_pre_view().
 *
 * Allows altering a view at the very beginning of views processing, before anything is done.
 */
function MY_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'my_view' && $display_id == 'entityreference' && _MY_MODULE_user_is_editor()) {
    $view->set_display('entityreference_all');
  }
}

This hook is never explicitly called by entityreference, so it's only executed when the display is executed in getReferencableEntities(). This is too late to switch displays, because initializeView() already sets handler options.

I fixed this by running $view->pre_execute() right after setting the display in initializeView().

    $this->view->set_display($display_name);
    $this->view->pre_execute();

See also: https://api.drupal.org/api/views/includes!view.inc/function/view::pre_ex...

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

SpadXIII’s picture

Status: Active » Reviewed & tested by the community

By running the $view->pre_execute(), the hook_views_pre_view is called before setting the entityreference-properties. This allows you to switch the display and still have a working entityreference autocomplete.

Seems to work great!

SocialNicheGuru’s picture

is this still needed?

MrHaroldA’s picture

@SocialNicheGuru: why should this not be needed anymore? The issue is still "open" and "RTBC"; not "closed" and "fixed".

dready2011’s picture

Yes, this is still needed. Just spend half a day trying to change the display of the entity reference view based on some business logic, and it kept returning an empty result after changing the display in hook_views_pre_view. After patching with this patch all is fine.

spotzero’s picture

Status: Reviewed & tested by the community » Fixed

Committed.

  • spotzero committed 5f416a3 on 7.x-1.x authored by MrHaroldA
    Issue #2292279 by MrHaroldA: Allow hook_views_pre_view() to alter the...

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.