Question

I am trying to find a way to limit Drupal Taxonomy Terms that appear on Content Add form based on their Role permissions but also on their user id. I have a taxonomy set called Departments (IT, Marketing, Accounting, etc).

On this specific content add form, there is a dropdown which asks you to assign the department that the content will belong to. I would like it to be the full dropdown list if the role is set as Admin however if the it is a regular user, I want it to instead be defaulted or locked to the department that they are assigned to in their user profile.

I looked around and have found multiple suggestions online such as setting up an entity reference field and using Taxonomy Access Control module but I can't seem to set it up correctly. Any suggestions?

Thanks!

Was it helpful?

Solution

I think the easiest way to achieve this would be a little code in a custom module.

First I would use hook_permisision to create a new permission called manually_set_department.

It is preferable to check for permissions not roles as roles can change and it is more flexible once a permission is set up as you can apply it to other roles if needed.

To do this use:

function MY_MODULE_permission() {
    return array(
        'manually_set_department' => array(
            'title' => t('Manually set department'),
            'description' => t('Allows users to manually set their department'),
        ),
    );
}

Now we need to cut down the list of departments if the user does not have the above permission. To do this we can use hook_form_alter. In this example I'm assuming your content type is called page:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

    drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'page_node_form':

            // dpm($form); // dpm (supplied by the devel module) is always useful for inspecting arrays

            if(!user_access('manually_set_department')) { // check the permission we created earlier

                global $user;
                $account = user_load($user->uid); // load the users account

                //dpm($account);

                $deparment_tid = $account->field_department[LANGUAGE_NONE][0]['tid']; // get their department tid

                foreach($form['field_department'][LANGUAGE_NONE]['#options'] as $k => $v) {
                    if($k != $deparment_tid) unset($form['field_department'][LANGUAGE_NONE]['#options'][$k]); // unset any but their own departments
                }

            }

            break;

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top