I have a table form created from a custom entity:
public function buildForm(array $form, FormStateInterface $form_state, $contract = NULL)
{
$form('subscriptions') = (
'#type' => 'table',
);
$form('subscriptions')('#header') = (some stuff here);
// here is the query to retrieve data from entity...
$results = db_query($query);
foreach ($results as $key => $value) {
$myKey = $key * 10;
$form('subscriptions')($myKey)('somefield') = ('#markup' => $value->designation);
$form('subscriptions')($myKey)('anotherfield') = (
'#type' => 'number',
'#default_value' => $value->$sTemp,
);
$form('subscriptions')($myKey)('addRow') = (
'#type' => 'submit',
'#name' => $myKey,
'#value' => '+',
'#ajax' => (
'callback' => '::ajaxAddRow',
'wrapper' => 'my_form_wrapper',
),
);
}
$form('submit') = (
'#type' => 'submit',
'#name' => 'submit',
'#value' => $this->t('Submit'),
);
return $form;
}
The ajax callback:
public function ajaxAddRow(array &$form, FormStateInterface $form_state)
{
$myKey = $form_state->getTriggeringElement()('#name');
$form('subscriptions')($myKey + 5) = $form('subscriptions')($myKey);
return $form;
}
The submitForm:
public function submitForm(array &$form, FormStateInterface $form_state)
{
if ($form_state->getTriggeringElement()('#name') == 'submit') {
do some stuff then exit the form
}
else {
$form_state->setRebuild();
}
}
When I click on ‘+’ in some row, the form is displayed again with a copy of the row added to the table.
But the copy is added at the end of the table.
How can I have the copy added just after the original one?