1

I want to add a button "Add More" with ajax for adding multiple fields I have writed this code, I don't understand why when I click to "add more" nothing work, there is an solution?

this is my code:

function produits_add($form, &$form_submit){

        if(!isset($form_state['num_names'])){
            $form_state['num_names']=1;
        }

        // Create wrapper for ajax
        $form['#prefix'] = '<div id="form-wrapper">';
        $form['#suffix'] = '</div>';

        for ($i = 0; $i < $form_state['num_names']; $i++) {

            $form['name_' . $i] = array(
                '#type' => 'textfield',
                '#title' => t('Name')

            );
        }

        $form['add_button']= array(
            '#type' => 'button',
            '#value'=> 'Add more',
            '#ajax' => array(
                'callback' => 'ajax_add_col',
                'method' => 'replace',
                'effect' => 'fade',
                'wrapper' => 'form-wrapper',
            ),
        );




        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Submit',
            '#submit' => array('produits_add_submit'),
        );





        return $form;
    }

    function ajax_add_col($form, &$form_state){

        $form_state['num_names']++;

        // rebuild whole form with new values
        $form_state['rebuild'] = true;
    }

function produits_add_submit($form, &$form_state){

// Some code
}
1

In your form function, group the textfields under a key, you can define your own key. I use group here.

// Create wrapper for ajax
$form['group']['#prefix'] = '<div id="form-wrapper">';
$form['group']['#suffix'] = '</div>';

for ($i = 0; $i < $form_state['num_names']; $i++) {

  $form['group']['name_' . $i] = array(
    '#type' => 'textfield',
    '#title' => t('Name')
  );
}

In your ajax callback, return part of the form.

function ajax_add_col($form, &$form_state){

  $form_state['num_names']++;

  // rebuild whole form with new values
  $form_state['rebuild'] = true;

  return $form['group'];
}
0

If anyone is still having this problem, like above please change your button type to submit. $form['add_button']= array( '#type' => 'button', '#value'=> 'Add more', '#ajax' => array( 'callback' => 'ajax_add_col', 'method' => 'replace', 'effect' => 'fade', 'wrapper' => 'form-wrapper', ), );


Change to

$form['add_button']= array( '#type' => 'submit', //change this submit '#value'=> 'Add more', '#submit' => array('ajax_example_add_more_add_one'),//add this to handle //your increment and rebuild form '#ajax' => array( 'callback' => 'ajax_add_col', 'wrapper' => 'form-wrapper',//returns the fieldset ), );

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.