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

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

Another way to limit the number of values of content type field is adding an extra validation on the node create/edit form. Assume we have a content type called center and a media field called field_center_video.
1. Create a custom module and add an extra validation.

function <module>_form_alter(&$form, &$form_state, $form_id) {  
  if ($form_id == 'center_node_form') {
    // Add the extra validation
    array_unshift($form['#validate'], 'addtional_validate');
  }
}

function addtional_validate($form, $form_state) {
  print_r($form_state);
  form_set_error('field_center_video', 'test');
}

 

Now we could not save the form because of the validation and we could get a list of values stored in the $form_state. Since there are different kinds of CCK fields so you may need to use different checking for the limitation. In this example, the field_center_video stored in the $form_state is in the format

[values] => Array
  (
  ...            
  [field_center_video] => Array
    (
      [0] => Array
        (
           =>
          [value] =>
          [_weight] => 0
        )

      [1] => Array
        (
           =>
          [value] =>
          [_weight] => 1
        )

      [field_center_video_add_more] => Add another item
    )
  ...

 

My addition_validation should look like

function addtional_validate($form, $form_state) {
  $count = 0;
  foreach($form_state['values']['field_center_video'] as $video) {
    if (!empty($video['value'])) {
      $count++;
    }
  }

  global $user;
  // Only allow to upload 2 videos for role = staff
  if (in_array('staff', $user->roles)) {
    if ($count > 2) {
      form_set_error('field_center_video', t('You cannot upload more than 2 videos'));
    }
  }
}

 

The approach should be better than then one we mentioned in Drupal – Limit the number of values of a content type field by role @ 1 because we could notify the user about the limitation using the form_set_error().

Done =)

Reference: Drupal – Add additional validation on Drupal form

2 thoughts on “Drupal – Limit the number of values of a content type field by role @ 2”

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s