Multiple Ajax forms on the same page

Hello,

I am writing a module for drupal 8. The purpose is to let users update the position values from a custom database table.

| id | position |
| 123 | [ 2 ] |
| 345 | [ 10 ] |

The following code displays a table with in each row (the result)

  • the id
  • the position in a textfield form that triggers an ajax function to update the value in the database

Unfortunately, the id value processed by the function saveAjax is always the first one an i can’t figure out why.
Can someone help ?

Here is mymodule/src/Controller/display.php

public function list() {
  // $query is database query to get elements i want to display
  $rows = array();
  foreach ($result = $query->execute()->fetchAll() as $r) {
    $rows[] = array(
      array('data' => $r->id),
      array('data' => Drupal::formBuilder()->getForm('DrupalmymoduleFormPositionForm',  $r->id, $r->position)),
)
  $content['table'] = array(
    '#type' => 'table',
    '#rows' => $rows,
  );
  return $content;
}

The mymodule/src/Form/PositionForm.php is

class PositionForm extends FormBase {

  public function getTitle() {
    return 'Modification de la position';
  }

  public function getFormId() {
    return 'PositionForm';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $id=NULL, $position=NULL) {

  $form['id']  = array('#type' => 'textfield','#value' => $id );
  $form['position'] = array(
    '#type' => 'textfield', '#size' => 3,
    '#default_value' => (isset($position))? (int)$position : '0',
     '#ajax' => array(
       'callback' => [$this,'saveAjax'],
       'progress' => array('type' => 'throbber', 'message' => '')),);
  return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    return TRUE;
  }

  public function saveAjax(array &$form, FormStateInterface $form_state) {

    $id       = $form_state->getValue('id');
    $position = $form_state->getValue('position');
    BbCrudController::update( 'mytable', $id, $position);
    dpm($id);
    dpm($position);
  }
}
Drupal version: 


Source: https://www.drupal.org/taxonomy/term/4/feed