Sat, 7 Dec 2013 15:50:09 EST
I have been doing a lot of Drupal 7 theming and module development for a recent project which requires high performance caching for several disperse
geographic locations. One of the modules monitors specific content types for changes, and only notifies exhibits upon a content change. I achieve this
by performing certain actions during frequent cron runs and a queue system.
The process requires views to be programmatically rendered using
views_get_view during a cron run. This was all working great until
I modified a content type to use entity reference fields. Each entity reference field is bound by the roles and users that created the original referenced content.
During my cron process, entityreference fields were being excluded from my views..but why?
Drupal 7 Cron Runs as an Anonymous User role
After lots of head scratching and permission fiddling (I was using unpublished content for the node reference fields), I scrounged up postings that mentioned Drupal
7 Cron runs as an Anonymous user. So we need our cron task to run as an authenticated user with better role permissions. But how?
How to run Drupal 7 Cron as a Different User
Thankfully in Drupal we can programmatically switch between users when needed. In this example I will switch from whatever the current user is to the administrator and back.
The current user in Drupal is always stored in the global $user variable. We swap users by loading a desired user, temporarily saving the currently logged in user, then switching between them while not modifying the session state.
global $user;
$original_user = $user;
$original_session_state = drupal_save_session();
drupal_save_session(FALSE);
$user = user_load(1);
## Do some work as admin
## Switch back to whatever the user was previously
$user = $original_user;
drupal_save_session($original_session_state);
Loading the views with entity reference fields during cron as administrator works with no issues. I hope this handy trick can help solve your issues as well.
Charles Palen has been involved in the technology sector for several years. His formal education focused on Enterprise Database Administration. He currently works as the principal software architect and manager at
Transcending Digital where he can be hired for your next contract project. Charles is a full stack developer who has been on the front lines of small business and enterprise for over 10 years. Charles current expertise covers the areas of .NET, Java, PHP, Node.js, Javascript, HTML, and CSS. Charles created
Technogumbo in 2008 as a way to share lessons learned while making original products.
Comments are currently disabled.