One of our website requirements is to have a content type that lets you decide on the total amount of form fields on the fly.

For example, if I specify a number 10, then it ought to generate the form fields consecutively; the text area and the checkbox form fields are created 10 times.

Essentially, to break it programmatically, it will create:

for(i = 0; i < 10; i++) {
  echo "<input type = 'textarea'></input>";
  echo "<select><option>1</option><option>2</option></select>";

This is pretty straightforward if I was dabbling with simple PHP files, but with Drupal 7's fields it is posing a bigger challenge than what it ought to be. I have tried exploring modules that let you create content types on the fly and considered creating a custom content type programmatically which seems like another challenge altogether.

I am curious if anybody has an alternative for this, and has dabbled with this challenge before.

  • 1
    I don't follow the question -- you want to create new content types on the fly OR you want to specify the number of fields to appear in the form for a given content type on the fly? Those are quite different things. Commented Jan 23, 2012 at 3:13
  • Charlie, I want to specify the number of fields to appear in the form for a given content type on the fly. Now this can be done if it was as straight forward as creating a content type field with the cardinality set to unlimited so the user can create as many content types. However, my goal is that when the Editor specifies X number of contents, then Commented Jan 23, 2012 at 8:54

1 Answer 1


If I understand you correctly, you're trying to change the cardinality of a field based on user input. You can do this by using field_update_field():

$field_name = 'field_bar';
$field = field_info_field($field_name);

$field['cardinality'] = 10;  // Change to number you want

// field_update_field() throws an exception on failure
try {
catch (Exception $e) {
  drupal_set_message(t('Could not update field.'), 'error');

As you can see, cardinality is actually a per-field setting: if you wanted to do this on a per-instance basis (so, separate cardinality for the field for each content type/bundle), you actually need to create an entirely new field for each bundle.

This would likely cause a number of issues, particularly if you wanted to do things like display the values in a view (each field would be handled separately, even though the only thing different is the name and the cardinality).

Instead, what I'd do is just set the cardinality of the field you want to be dynamic to "unlimited" (FIELD_CARDINALITY_UNLIMITED in code): out of the box you get a fancy widget that lets users add as many values as they'd like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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