I try to implement a button to add rows to a form table. Each clic on the button should add a new line.
My problem is that my modifications in the AJAX Callback doesn't seem to modify the actual $form object :
At the first clic, row n°6 is added but without default values, wich is already a problem. The next clics have no effect, the $form parameter in the callback doesn't contain the 6th row.
What is the way to actually modify $form ?
Here is the build form :
public function buildForm(array $form, FormStateInterface $form_state, Array $profile = NULL) {
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit'),
);
// table
$form['myTable'] = array(
'#type' => 'table',
'#header' => array(t('COL 1'), t('COL 2'), t('COL 3')),
'#prefix' => '<div id="my-table-wrapper">',
'#suffix' => '</div>',
);
// Build the table rows and columns.
for ($cpt = 0; $cpt <= 5; $cpt++) {
// Table row
$form['myTable'][$cpt] = $this->getTableLine($cpt);
}
$form['addRow'] = array(
'#type' => 'button',
'#value' => t('Add a row'),
'#ajax' => array(
'callback' => '::ajaxAddRow',
'event' => 'click',
'wrapper' => 'my-table-wrapper',
),
);
return $form;
}
Here the function called to fill the rows :
function getTableLine($key) {
$line = array();
$line['col_1'] = array(
'#type' => 'textfield',
'#default_value' => 'col 1 - row ' . $key,
);
$line['col_2'] = array(
'#type' => 'textfield',
'#default_value' => 'col 2 - row ' . $key,
);
$line['col_3'] = array(
'#type' => 'textfield',
'#default_value' => 'col 3 - row ' . $key,
);
return $line;
}
And the Ajax callback :
function ajaxAddRow($form, $form_state) {
$cpt=0;
for ($x = 0; $x <= 10 & $form['myTable'][$x]; $x++) {
$cpt++;
}
// $cpt always return 6 - expected to increment
// $form['myTable'][$cpt] is always empty
$form['myTable'][$cpt] = $this->getTableLine($cpt);
return $form['myTable'];
}