munge83
munge83

Reputation: 153

Limit user role on multiple field

I know that I can make two different field types and assign different roles to them. Because of using views, custom searches, and gmaps, and because this will be applied to Field collection I really need this kind of approach to the problem.

I tried to crate custom module that will limit role staff to only be able to insert two field_text into node but administrator can insert as many as he wont. field_text Number of values is set to Unlimited and Content type name is youtube. I found this for drupal 6 but I don't know how to code it in drupal 7.

function myformlimit_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'youtube') {
global $user;
// Only allow to insert 2 text for role = staff
if (in_array('staff', $user->roles)) {
  $text_limit = 2;
  $form['#field_info']['field_text']['multiple'] = $text_limit;
  $i = 1;
  foreach ($form['field_text'] as $key => $value) {
    if (is_numeric($key)) {
      if ($i > $text_limit) {
        unset($form['field_text'][$key]);
      }
      $i++;
    }
  }
}
}
 }

Upvotes: 0

Views: 50

Answers (1)

Muhammad Reda
Muhammad Reda

Reputation: 27023

Well you are half way there. You can use the following code to get you the idea.

Kindly note that I named my field field_test_field, you can replace that with your field's name.

function myformlimit_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'youtube_node_form')
    {
        global $user;
        if(in_array('staff', $user->roles))
        {
            if($form_state['field']['field_test_field'][LANGUAGE_NONE]['items_count'] >= 2)
            {
                unset($form['field_test_field'][LANGUAGE_NONE]['add_more']);
            }
        }
    }
}

Upvotes: 1

Related Questions