Drupal – Limit the number of values of a content type field by role @ 1

Sometimes will be want to restrict the number of values of content type field by roles. In that case, we could create a custom module and alter the node create/edit form. The following example will unset any field values which are outside the limit.

Assume we have a content type called center and a multiple image fields called field_center_image.

function <module>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'center_node_form') {
    global $user;
    // Only allow to upload 2 images for role = staff
    if (in_array('staff', $user->roles)) {
      $center_image_limit = 2;
      $form['#field_info']['field_center_image']['multiple'] = $center_image_limit;
      $i = 1;
      foreach ($form['field_center_image'] as $key => $value) {
        if (is_numeric($key)) {
          if ($i > $center_image_limit) {
            unset($form['field_center_image'][$key]);
          }
          $i++;
        }
      }
    }
  }
}

 

Now if the staff user trying to upload more than 2 images, those extra images will be unset and will not be saved.

Done =)

Reference: StackOverflow – change field’s number of values per role

Next: Drupal – Limit the number of values of a content type field by role @ 2

One thought on “Drupal – Limit the number of values of a content type field by role @ 1”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.