`

ajax 添加相同的表单

 
阅读更多
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '<div id="names-fieldset-wrapper">',
    '#suffix' => '</div>',
  );

  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset'][$i]['name']= array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['names_fieldset'][$i]['hobby'] = array(
      '#type' => 'select',
      '#title' => t('Hobby'),
      '#options' => drupal_map_assoc(array('足球','电影','乒乓')),
      '#description' => ' 请选择你的爱好!',
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('ajax_example_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function ajax_example_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

function ajax_example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}


function ajax_example_add_more_submit($form, &$form_state) {
  $output = t('These people are coming to the picnic: @names',
    array('@names' => implode(', ', $form_state['values']['names_fieldset']['name'])) );
  drupal_set_message($output);
}

 

  • 大小: 23.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics