简体   繁体   中英

Drupal Custom Module / Form Question: Adding an array of fields

I'm creating a custom module where I'd like to have the "add another item" functionality for a particular field, but I can't seem to figure out what I need to do in order to accomplish this... I've been going through Drupal forums and their Forms API Reference, but I must not be getting something.... I'm using Drupal 6.20, and in my module, I tried:

  $form['options'] = array(
    '#title' => t('Options'),
    '#type' => 'fieldset',
  );
  $form['options']['address'] = array(
    '#type'=>'textfield',
    '#title'=>t('Address'),
    '#tree' => 1,
  );

Thinking I would get an text input that looked like this:

<input type="text" class="form-text text" value="" size="60" id="edit-address-0-value" name="address[0][value]">

But, I just get an input that looks like this:

<input type="text" class="form-text" value="" size="60" id="edit-address" name="address" maxlength="128">

You need to set #tree on the element above the one you want to duplicate. FAPI will store values in a tree structure from that element on downwards.

To get a name like address[0][value] you will need something like

  $form['options']['address'] = array(
    '#tree' => TRUE,
  );
  $form['options']['address'][0] = array(
    '#tree' => TRUE,
  );
  $form['options']['address'][0]['value'] = array(
    '#type'=>'textfield',
    '#title'=>t('Address'),
  );

But you don't need the [value] part unless you are actually trying to achieve multi-valued grouped fields or if your field has a complex (custom) data type implemented with multiple PHP values (ie. latitude/longitude, start/stop dates, etc.).

You will also probably need to store the number of values in something like $form['options']['#nb_values'] or in an hidden field (if you plan to add the additional fields to the form using JavaScript).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM