3

I have created a field programmatically that has 'cardinality' => FIELD_CARDINALITY_UNLIMITED. This is the functionality that I want. I want users to be able to add as many items as they need to. However, when the form first shows, I'd like to have 3 blank fields ready to be filled out before having to click the "Add another item" button. Is this possible?

Lots of answers on the web about how to set the cardinality, but that's not what I'm looking to do. I just want to show 3 blank ones to get started while still keeping my cardinality as unlimited. I hope this question makes sense.

1

You can alter your form to add your proposed blank fields , to do that you need to implement hook_form_alter in your module and inside you would have :

if (empty($form_state['field_counter'])) {
  $form_state['field_counter'] = 3;
}
else if($form_state['field_counter'] < 3)
{
  $form_state['field_counter'] = 3;
}
for ($i = 0; $i < $form_state['field_counter']; $i++) {
  $form['YOUR FIELD NAME'][$i] = array(
    '#type' => 'textfield',
    '#title' => t('Your Lable'),
  );
}
| improve this answer | |
  • Thank you so much! I got it to work using this. It was difficult because I had a pretty complicated custom field inside a field collection, but I finally got it to work. – mlanning Mar 2 '16 at 17:20
  • I am having one problem though. Now when I click the "Add another" button, I don't get a new field until the third time I click the button. – mlanning Mar 2 '16 at 17:53

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.