0

I'm doing a job listings site. Users with privileges to list jobs have an Entity Reference field connecting them to a Company node. Job nodes have a similar field. So when an employer creates a Job, he should only be able to choose the Company in his own ER field.

This much I can do: I just created an Entity Reference View and limited it with a Referencing Entity Relationship and a Current User filter that uses that Relationship.

So far so good.

However, admins should be able to create Jobs for any Company. This is where I fall down. It seems like there's nothing I can do inside this View, since everything in this View has to do with the nodes being listed; there's no way to conditionally turn off a filter based on the current user.

So now I need other options. I see the obvious workaround: Make the User Company field accept multiple values, and give every single one to every admin user. That will be my last resort. Before I give up and go that route, does anyone have any ideas? Any answer will do, though if yours requires my admin users to grant themselves new permissions every time we create a company, I will probably disregard it. Thanks!

  • 2
    You can try to use a view hook on the ERV to check the user ID and then prune out results as needed. – mpdonadio Mar 22 '13 at 20:06
  • Have a look at hook_views_plugins_alter to disable the filter or the relationship for admin users only. – Triskelion Mar 22 '13 at 22:43
1

The solution was to use hook_views_pre_build. That hook lets you edit the view's criteria before it actually gets run. Here's my full code:

function mymodule_permission() { // Create the permission for privileged users
    return array(
        'create jobs for any company' => array(
            'title' => t('Create Jobs for any Company'),
            'description' => t("Don't limit the Company field in the Job node type to only those Companies assigned to the user."),
        ),
    );
}

function mymodule_views_pre_build(&$view) {
    /* If it's the right view and the user has the above permission… */
    if($view->name === 'job_company_entity_reference' && user_access('create jobs for any company')) {
        /* …then get rid of the view criteria that limit the choices for everyone else.
        (I found these by enabling the devel module and calling dpm($view) at the top of this function.) */
        unset($view->filter['uid_current']);
        unset($view->relationship['reverse_field_company_user']);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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