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

Advertisements

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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