I am using Drupal 9. I am creating a module that has a form with a button that will re-create another form similar to the first one.
These is my code.
public function buildForm(array $form, FormStateInterface $form_state) {
$database = \Drupal::database();
$result = $database->select('user_details', 'u')
->fields('u', ['uid']);
$row = $result->execute()->fetchAll();
$rowCount = count($row);
$form['buttons_multiple'] = [
'#type' => "container",
'#attributes' => ['style' => 'margin-top: 2em;'],
'add_chat' => [
'#type' => 'submit',
'#value' => $this->t('Add form +'),
'#attributes' => [
'style' => 'font-size: 1.2em;',
],
'#submit' => ['::addForm'],
],
];
for ($counter = 1; $counter <= $rowCount; $counter++) {
$form['form_box_' . $counter] = [
'#type' => "container",
'full_name'.$counter => [
'#type' => 'textfield',
'#title' => 'name',
'#size' => 12,
'#required' => TRUE,
],
'buttons_single' => [
'#type' => "container",
'save'.$counter => [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#attributes' => [
'style' => 'font-size: 1em;',
],
'#submit' => ['::submitForm'],
],
],
'count' => [
'#type' => 'hidden',
'#value' => $counter,
],
];
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$name = $form_state->getValue('full_name');
$counter = $form_state->getValue('count');
$form_state->set('user_values', [
'name' => $form_state->getValue('name'),
]);
// For testing purpose. Display full name
$this->messenger()->addMessage($this->t('Hi, your name is %name.', ['%name' => $name]));
}
public function addForm(array &$form, FormStateInterface $form_state) {
$values = [
[
'full_name' => '',
],
];
$database = \Drupal::database();
$query = $database->insert('user_details')->fields(['full_name']);
foreach ($values as $details) {
$query->values($details);
}
$query->execute();
}
Based on the code above, I only get the name of the last added form even if I clicked the saved button of the first form.
How will I work on the saved button for each form?
Thank you in advance.