How do I create an AJAX form with Add and Remove buttons for multi-value form element without submission button?

I would like to create a custom form with a textfield in which I input some data and it gets saved in the variable table.

The form should only contain the Add, Remove, and Add more button to add additional textfields.

When the textfield is empty, there should be an Add button; when the textfield is not empty, there should be a Remove button.
Clicking on the Add more button should create an empty textfield with an Add button.

All this need to happen without page reload.

I was able to add the Add, Remove, Add more, and Submit buttons.
I looked into the available resources and example modules, but I can’t find helpful resources.

Can anyone help me to modify the code so that the Submit button can be removed?

function mymodule_menu() {
    $items = array();
    $items['admin/mymodule'] = array(
        'title' => t('Example form'),
        'type' => MENU_CALLBACK,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('mymodule_ajax_example_add_more'),
        'access callback' => TRUE,
    );

    return $items;
}

function mymodule_ajax_example_add_more($form, &$form_state) {
  $mymodule_ajax_events = variable_get('mymodule_ajax_example_content', array());
  $mymodule_ajax_events_count = count($mymodule_ajax_events);
  if ($mymodule_ajax_events_count == 0) {
    $mymodule_ajax_events_count = 1;
  }

  $form = array();
  $form['#tree'] = TRUE;
  $form['mymodule_ajax_events'] = [
    '#type' => 'container',
    '#weight' => 80,
    '#tree' => TRUE,
    // Set up the wrapper so that AJAX will be able to replace the fieldset.
    '#prefix' => '<div id="js-ajax-elements-wrapper">',
    '#suffix' => '</div>',
  ];
  $form_state['field_deltas'] = isset($form_state['field_deltas']) ? $form_state['field_deltas'] : range(0, $mymodule_ajax_events_count-1);

  $field_count = $form_state['field_deltas'];
  foreach ($field_count as $delta) {
    $form['mymodule_ajax_events'][$delta] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['container-inline'],
      ],
      '#tree' => TRUE,
    ];

    $form['mymodule_ajax_events'][$delta]['event_url'] = [
      '#type' => 'textfield',
      '#title' => t('Event URL' . ($delta + 1)),
      '#size' => 40,
      '#default_value' => (isset($mymodule_ajax_events[$delta])) ? $mymodule_ajax_events[$delta] : '',
    ];

    $form['mymodule_ajax_events'][$delta]['remove_event_url'] = array(
      '#type' => 'submit',
      '#value' => t('Remove'),
      '#submit' => ['mymodule_ajax_example_add_more_remove'],
      '#ajax' => [
        'callback' => 'mymodule_ajax_example_add_more_remove_callback',
        'wrapper' => 'js-ajax-elements-wrapper',
      ],
      '#weight' => 50,
      '#attributes' => [
        'class' => ['button-small'],
      ],
      '#name' => 'remove_event_url_' . $delta,
    );
  }

  $form['mymodule_ajax_events']['add_event_url'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => ['mymodule_ajax_example_add_more_add_one'],
    '#ajax' => [
      'callback' => 'mymodule_ajax_example_add_more_add_one_callback',
      'wrapper' => 'js-ajax-elements-wrapper',
    ],
    '#weight' => 1,
  );
    $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 100,
  );

  return $form;
}

function mymodule_ajax_example_add_more_remove($form, &$form_state) {
  $delta_remove = $form_state['triggering_element']['#parents'][1];
  $k = array_search($delta_remove, $form_state['field_deltas']);
  unset($form_state['field_deltas'][$k]);

  $form_state['rebuild'] = TRUE;
  drupal_get_messages();
}

function mymodule_ajax_example_add_more_remove_callback($form, &$form_state) {
  return $form['mymodule_ajax_events'];
}

function mymodule_ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['field_deltas'][] = count($form_state['field_deltas']) > 0 ? max($form_state['field_deltas']) + 1 : 0;
  //mymodule_ajax_example_add_more_validate();
  $form_state['rebuild'] = TRUE;
  // drupal_get_messages();
}

function mymodule_ajax_example_add_more_add_one_callback($form, $form_state) {
  return $form['mymodule_ajax_events'];
}

function mymodule_ajax_example_add_more_validate($form, $form_state) {
    dpm($form_state);
  foreach ($form_state['values']['mymodule_ajax_events'] as $key => $item) {
      //dpm($item);
      dpm($item['event_url']);
   if (!empty($item['event_url'])) {
      if (!preg_match('/https://example.com.*/i', $item['event_url'])) {
        form_set_error("mymodule_ajax_events][$key][event_url", 'Enter a valid Event URL.' . ($key + 1));
        //
      }else{
       drupal_set_message('URL ' . ($key + 1) . ' Created' );
   }
  }
 }
}

function mymodule_ajax_example_add_more_submit($form, $form_state) {
  $events_content = array();
  $events_count = 0;
  foreach ($form_state['values']['mymodule_ajax_events'] as $key => $item) {
    if (!empty($item['event_url'])) {
      $events_content[] = $item['event_url'];
      $events_count++;
   }
 }
  variable_set('mymodule_ajax_example_content', $events_content);
  variable_set('mymodule_ajax_example_count', $events_count);
}
This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

How do I create an AJAX form with Add and Remove buttons for multi-value form element without submission button?

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.