0

I'm implementing ajax add more example in my own module. I am pulling data from an Oracle database and printing children's data. However, when I click Add Person, the 1st child's data is multiplied several times, 2nd child's data is multiplied several times and so on. How can I multiply only the last child's fieldset once?

My code:

function suweb_agi_add_more_callback($form, &$form_state) {
  return $form['c'];
}
function suweb_agi_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}
function suweb_agi_add_more_remove_one($form, &$form_state) {
  $form_state['id']=$form_state['clicked_button']['#attributes']['data-id']+1;
}
..
..
..
function suweb_agi_form(&$form, &$form_state, $form_id) {
  for ($x=0;$x<count($child);$x++) {
    for ($y=0;$y<$form_state['num_names'];$y++) {
      $form['c'][$x][$y]['info'] =  [
        '#type' => 'fieldset',
        '#title' => ($lang == 'tr')?'Çocukları / Bakmakla Yükümlü Olduğu Kişilerin Durumu':'Status of Children Dependent On or Living With The Taxpayer',
        '#collapsed' => false,
        '#collapsible' => false,
        '#prefix' => '<div id="agi-fieldset-wrapper">',
        '#suffix' => '</div>',
        'info' => [
          '#type' => 'markup',
          '#markup' => ($lang == 'tr')?'Çocuğunuz 18 yaşından büyük ve eğitimine devam ediyorsa; eğitim durumu bilgilerini doldurunuz. Eğitimine devam etmiyor ise, Asgari Geçim İndirimi kapsamında değildir. Çocuğunuz 24 yaşından büyük ise Asgari Geçim İndirimi kapsamında değildir.':'If your other is older than 18 and continuing his/her education, fill out the education status information. If he/she is not continuing his/her education, he/she is not covered in the Minumum Living Allowance. If your other is older than 24, he/she is not covered in the Minumum Living Allowance.',
          '#prefix' => '<span class="agi-warning">',
          '#suffix' => '</span>'
        ],
      ];
      $form['c'][$x][$y]['info']['first_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Ad':'Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['CHILD_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['middle_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Orta Ad':'Middle Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['CHILD_MIDDLE_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['last_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Soyad':'Last Name',
        '#default_value' => $person['LASTNAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['tckn'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'T.C. Kimlik No':'T.C. Identity Number',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['TC_KIMLIK_NO'],
        '#attributes' => [
          'class' => ['tckn'],
        ],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['birth_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Doğum Tarihi':'Date of Birth',
        '#default_value' => ($form_state['num_names']>1)?'':date('Y-m-d',strtotime($child[$x]['BIRTH_DATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-30:+0',
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['father_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Baba Adı':'Father\'s Name',
        '#default_value' => $person['CINSIYET'] == 'M'?$person['FIRSTNAME']:$other['SPOUSE_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['mother_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Anne Adı':'Mother\'s Name',
        '#default_value' => $person['CINSIYET'] == 'F'?$person['FIRSTNAME']:$other['SPOUSE_FIRST_NAME'],
        '#size' => 20,
        '#maxlength' => 20,
      ];
      $form['c'][$x][$y]['info']['gender'] = [
        '#type' => 'radios',
        '#title' => ($lang == 'tr')?'Cinsiyeti':'Gender',
        '#options' => ($lang == 'tr')?['F'=>'Kız','M'=>'Erkek']:['F' => 'Girl','M' => 'Boy'],
        '#default_value' => ($form_state['num_names']>1)?'':trim($child[$x]['GENDER']),
      ];
      $form['c'][$x][$y]['info']['studying'] = [
        '#type' => 'checkbox',
        '#title' => ($lang == 'tr')?'Çalışıyor mu?':'Studying?',
        '#default_value' => (isset($child[$x]['SCHOOL_NAME']))?1:0,
      ];
      $form['c'][$x][$y]['info']['education'] = [
        '#type' => 'fieldset',
        '#title' => ($lang == 'tr')?'Eğitim Bilgileri':'Education Details',
        '#collapsed' => false,
        '#collapsible' => false,
        '#states' => [
          'visible' => [
            ':input[name="c['.$x.'][0][info][studying]"]' => ['checked' => TRUE],
          ],
        ],
      ];
      $form['c'][$x][$y]['info']['education']['education_type'] = [
        '#type' => 'select',
        '#title' => ($lang == 'tr')?'Eğitim Tipi':'Education Type',
        '#options' => ($lang == 'tr')?[0=>'İlköğretim',1=>'Lise',2=>'Üniversite']:[0=>'Primary School',1=>'High School',2=>'University'],
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['EDUCATION_TYPE'],
      ];
      $form['c'][$x][$y]['info']['education']['school_name'] = [
        '#type' => 'textfield',
        '#title' => ($lang == 'tr')?'Okulun Adı':'School\'s Name',
        '#default_value' => ($form_state['num_names']>1)?'':$child[$x]['SCHOOL_NAME'],
      ];
      $form['c'][$x][$y]['info']['education']['school_start_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Okulun Başlangıç Tarihi':'School Start Date',
        '#default_value' => (!isset($child[$x]['SCHOOL_START_DATE']))?'':date('Y-m-d',strtotime($child[$x]['SCHOOL_START_DATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-18:+0'
      ];
      $form['c'][$x][$y]['info']['education']['school_end_date'] = [
        '#type' => 'date_popup',
        '#title' => ($lang == 'tr')?'Okulun Bitiş Tarihi':'School End Date',
        '#default_value' => (!isset($child[$x]['SCHOOL_END_DATE']))?'':date('Y-m-d',strtotime($child[$x]['SCHOOL_END_DATE'])),
        '#date_format' => 'd/m/Y',
        '#date_year_range' => '-18:+10'
      ];
      $form['c'][$x][$y]['info']['remove_person'] = [
        '#type' => 'submit',
        '#value' => ($lang == 'tr')?'Kişi Sil':'Remove Person',
        '#submit' => ['suweb_agi_add_more_remove_one'],
        '#attributes' => ['style' => 'float:right', 'data-id' => $x],
        '#ajax' => [
          'callback' => 'suweb_agi_add_more_callback',
          'wrapper' => 'agi-fieldset-wrapper',
        ],
      ];
    }
  }
  $form['add_person'] = [
    '#type' => 'submit',
    '#value' => ($lang == 'tr')?'Kişi Ekle':'Add Person',
    '#submit' => ['suweb_agi_add_more_add_one'],
    '#ajax' => [
      'callback' => 'suweb_agi_add_more_callback',
      'wrapper' => 'agi-fieldset-wrapper',
    ],
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => ($lang == 'tr')?'Bilgileri Güncelle ve Yazdır':'Save Information and Print',
  ];
  return $form;
}
0
+50

You have double for-loop in your provided code.. Here is an example how it could be done. The code is not tested but should work and is only the an example for the approach.

function suweb_agi_add_more_add_one($form, &$form_state) {
  // We want to add one more fieldset, so lets signalize that.
  $form_state['add_more'] = TRUE;
  // And build the form with the new form_state again.
  $form_state['rebuild'] = TRUE;
}

function suweb_agi_form(&$form, &$form_state, $form_id) {
  // Don't know where you get $child from.. but let's assume, you have it from somewhere.
  // And it is an array.
  $child = array();
  for ($x=0;$x<count($child);$x++) {
    // First you should create the form for existing data.
    $form['c'][$x]['info'] =  [
      '#type' => 'fieldset',
      // Use the t()-function and do your translations not in your functions!!
      '#title' => t('Status of Children Dependent On or Living With The Taxpayer'),
      '#collapsed' => false,
      '#collapsible' => false,
      '#prefix' => '<div id="agi-fieldset-wrapper">',
      '#suffix' => '</div>',
      'info' => [
        '#type' => 'markup',
        // Use the t()-function and do your translations not in your functions!!
        '#markup' => t('If your other is older than 18 and continuing his/her education, fill out the education status information. If he/she is not continuing his/her education, he/she is not covered in the Minumum Living Allowance. If your other is older than 24, he/she is not covered in the Minumum Living Allowance.'),
        '#prefix' => '<span class="agi-warning">',
        '#suffix' => '</span>'
      ],
    ];
    // [...]
  }

  // Now you can check if there is the request for add more..
  if (!empty($form_state['add_more']) && $form_state['add_more']) {
    // Copy the latest form element.
    $latest_form_element = end($form['c']);
    // Change some values, i.e. the id you use for delete functionality.
    $latest_form_element['xyz']['#attributes']['data-id'] += 1;
    // And then add it to the element
    $form['c'][] = $latest_form_element;
    // Reset the form_state add_more
    $form_state['add_more'] = FALSE;
  }

  $form['add_person'] = [
    '#type' => 'submit',
    '#value' => t('Add Person'),
    '#submit' => ['suweb_agi_add_more_add_one'],
    '#ajax' => [
      'callback' => 'suweb_agi_add_more_callback',
      'wrapper' => 'agi-fieldset-wrapper',
    ],
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => t('Save Information and Print'),
  ];
  return $form;
}
3
  • The only problem with this that it duplicates the first child, omitting First Name textfield. I have no clue why. I think it was happening before as well.
    – Kartagis
    Oct 31 '16 at 10:23
  • My bad, I should have reset the value, not the textfield itself. Thank you :)
    – Kartagis
    Oct 31 '16 at 13:11
  • Hrm, after much trying, I found another issue. If the number of childen aka count($child) is zero, I get Warning: end() expects parameter 1 to be array, null given
    – Kartagis
    Nov 9 '16 at 13:34

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.