Hi,
I've created a form and themed it as a table using D7 form API.
I want to add a 'delete' button to each row that will remove the row on which the button was clicked (via Ajax - w/o page refresh).

My problem is: how to determine inside the Ajax callback function which row was clicked?
Each row had a unique id, each button has a unique name and id, I can see in the $form_state that there is an entry called: "_triggering_element_name" which contains the name of the clicked button, but somehow it doesn't seem to be a the correct way to do it...

some code:

// form build 
function form_build {
  ...
  for ($i ... ) {
    $form['items']["delete$i"] = array(
      '#type' => 'submit',
      '#name' => "remove$i",
      '#value' => t('Delete'),
      '#submit' => array('myform_del_item'),
      '#ajax' => array(
        'callback' => 'mymodule_form_callback_items',
        'wrapper' => 'item-div',
        'effect' => 'fade',
        'progress' => array('type' => 'none'),
      ),
    );
  }
}

/**
 * only select the portion of the form to be updated.
 */
function mymodule_form_callback_items($form, $form_state) {
  return $form['items'];
}

/**
 * Submit handler for the "delete" button.
 */
function myform_del_item($form, &$form_state) {
  // 1. get row id / button id ???
  // 2. delete row
  $form_state['rebuild'] = TRUE; // force rebuilt the form
}

Any help is appreciated,
Thanks.

Comments

neutecake’s picture

Same question here

amirn’s picture

Here is one option of doing it:

for ($i ..) {
    $form[...]
    $form['items']["delete$i"] = array(
      '#type' => 'submit',
      '#name' => "remove$i",
      '#value' => t('Delete'),
      '#indx' => $i, // index for deletion
      '#submit' => 'dummy_del_item',
      '#ajax' => array(
        'callback' => 'mymodule_del_item_callback',
        'progress' => array('type' => 'none'),
      ),
    );
  }


function mymodule_del_item_callback($form, &$form_state) {
  $indx = $form_state['triggering_element']['#indx'];
  // some server side delete logic in here if needed
  $selector = "#items_del_".$indx;
  $commands = array();
  $commands[] = ajax_command_remove($selector);
  return array('#type' => 'ajax', '#commands' => $commands);
}

// I've added the ID for each row in my table theme function:
...
$rows[] = array('data' => $row, 'id' => 'items_del_' . $i);
...

nikathone’s picture

Hi amirn,

I've tried what you suggested but my button is deleting one item at a time. for example if I have a two text fields and a button on a row, it will delete first the text field in column one then the next one then the button. I think may it's the way I initialise my rows which might be wrong. Can you please show me how did you initialise the variable $row with the textfield.

Thank you

Marko B’s picture

I am having the same problem as nikathone. I keep deleting only one row of data.

itsnadeem’s picture

You can see how to use ajax API in Drupal 8 and 9 in this article. Also see the sample code here.