radhakrishnan vivek
radhakrishnan vivek

Reputation: 1001

dynamically adding text boxes in drupal form api

I want to have a add more button on clicking which i can add dynamically, textboxes in a drupal form api.. can someone help on this?

Thanks in advance

Upvotes: 2

Views: 4945

Answers (2)

Triss
Triss

Reputation: 96

Here is an example how to solve this with Ajax in Drupal 7(If anyone want I can convert it also to Drupal 6 using AHAH(name before it became Ajax)).

<?php


function text_boxes_form($form, &$form_state)
{
    $number = 0;
    $addTextbox = false;

    $form['text_lists'] = array
    (
        '#tree' => true,
        '#theme' => 'my_list_theme',
        '#prefix' => '<div id="wrapper">',
        '#suffix' => '</div>',
    );

    if (array_key_exists('triggering_element', $form_state) &&
        array_key_exists('#name', $form_state['triggering_element']) &&
        $form_state['triggering_element']['#name'] == 'Add'
    ) {
        $addTextbox = true;
    }

    if (array_key_exists('values', $form_state) && array_key_exists('text_lists', $form_state['values']))
    {
        foreach ($form_state['values']['text_lists'] as $element) {
            $form['text_lists'][$number]['text'] = array(
                '#type'  => 'textfield',
            );
            $number++;
        }
    }
    if ($addTextbox) {
        $form['text_lists'][$number]['text'] = array(
            '#type'  => 'textfield',
        );
    }

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

    return $form;
}

function ajax_add_textbox_callback($form, $form_state)
{
    return $form['text_lists'];
}

function text_boxes_menu()
{
    $items = array();

    $items['text_boxes'] = array(
        'title'           => 'Text Boxes',
        'description'     => 'Text Boxes',
        'page callback'   => 'drupal_get_form',
        'page arguments'  => array('text_boxes_form'),
        'access callback' => array(TRUE),
        'type'            => MENU_CALLBACK,
    );

    return $items;
}

Upvotes: 0

Laxman13
Laxman13

Reputation: 5211

Take a look at Adding dynamic form elements using AHAH. It is a good guide to learn AHAH with Drupal's form API.

EDIT: For an example, install the Examples for Developers module, it has an AHAH example you can use to help you learn.

Upvotes: 2

Related Questions