Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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...
Comment | File | Size | Author |
---|---|---|---|
entityreference_pre_execute_pre_view.patch | 616 bytes | MrHaroldA | |
Comments
Comment #1
SpadXIII CreditAttribution: SpadXIII commentedBy 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!
Comment #2
SocialNicheGuru CreditAttribution: SocialNicheGuru commentedis this still needed?
Comment #3
MrHaroldA CreditAttribution: MrHaroldA commented@SocialNicheGuru: why should this not be needed anymore? The issue is still "open" and "RTBC"; not "closed" and "fixed".
Comment #4
dready2011 CreditAttribution: dready2011 commentedYes, 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.
Comment #5
spotzero CreditAttribution: spotzero at Coldfront Labs Inc. commentedCommitted.