AnswerBun.com

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

Drupal Answers Asked by miststudent2011 on December 4, 2020

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);
}

One Answer

If you want to omit the submit button altogether, you need to move the logic of the validate and submit to the ajax callbacks.

First, remove the submit button:

$form['submit'] = [
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#weight' => 100,
];

Now you can take the logic from mymodule_ajax_example_add_more_validate and from mymodule_ajax_example_add_more_submit to the various ajax callbacks.

Each time the user interacts with the ajax buttons, you must validate the data and if all goes well, rewrite the variable to the database, because as far as we concern, this was the last interaction the user has with this form.

Answered by JonnieJS on December 4, 2020

Add your own answers!

Related Questions

How can I rebuild an image field with values in an Ajax callback?

1  Asked on December 17, 2020 by wassim-akermi

     

Breadcrumb/block settings

3  Asked on December 17, 2020 by zach

       

Change can I programmatically change the format of a view?

2  Asked on December 16, 2020 by user78498

   

How do I create a conditional form field?

2  Asked on December 15, 2020 by sean

 

I need to reference a custom field I created in User Profile

1  Asked on December 15, 2020 by user17021

     

How to use the uc_csv module for getting reports

1  Asked on December 15, 2020 by sathish

     

CKEditor displays entire site page when rich text is switched on

1  Asked on December 13, 2020 by amit-sedai

 

How do I get the video media path in a theme?

1  Asked on December 12, 2020 by mrfox

 

drush cannot update commerce kickstart

1  Asked on December 9, 2020 by ckosloff

   

How to add a javascript function after uploading file

2  Asked on December 9, 2020 by ahmed

   

Creating date field with only month and year

2  Asked on December 8, 2020 by blaine-lang

   

submitForm() isn’t called

1  Asked on December 7, 2020 by dylhof

     

Get the uri/path value of an image in the field template

2  Asked on December 7, 2020 by flamesquirrel

       

User registration silently fails – how to debug?

1  Asked on December 5, 2020 by druvision

     

How can I automatically flag new comments?

1  Asked on December 5, 2020 by sdfff

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir