5

How do I force an unlimited number of values using code for a field I created using the Field API in Drupal 7? In this case it doesn't make sense to have any other setting so every time I create an instance of this field I have to set the number of values from 1 to unlimited.

5

You mean for a field type that you created yourself?

There is no real API to declare that, the only thing you can do is alter the add/edit field form.

I've already done this myself for the Properties module; here is the code (source):

function properties_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  if ($form['#field']['type'] == 'properties') {
    // Hide the cardinality setting on the field settings for properties fields.
    $form['field']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
    $form['field']['#access'] = FALSE;
  }
}

(Don't forget to flush the cache after changing form_alter hooks and, if it's an instance setting, delete and recreate the instance to remove the previous default)

| improve this answer | |
  • Works. It seems like something that should be configured in hook_field_info(). – Adam S May 6 '11 at 19:54
  • Only problem with this is the user has to submit the form to save the value. By default the form cardinality is not unlimited until they save the edit field settings form. – user11146 Nov 2 '12 at 15:03
1

The answer using hook_form_field_ui_field_edit_form_alter() works, but it hides the Field visibility and permissions as well as the cardinality. I prefer to just disable the cardinality:

$form['field']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
$form['field']['cardinality']['#disabled'] = TRUE;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.