I am using Drupal 8 and I am creating multiple forms that are made of a #tree hierarchy.
I need to retrieving the value of the "first name" from the #tree using the below code and it doesn't get the value.
$firstName = $form_state->getValue('userBoxArea')[$count]['userBox']['nameBox']['firstName'];
This is my code:
protected static $formID;
public function getFormId() {
if (empty(self::$formID)) {
self::$formID = 1;
}
else {
self::$formID++;
}
return 'formID' . self::$formID;
}
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['userBoxArea' ] = [
'#type' => 'container',
'#tree' => TRUE,
];
for($counter = 0; $counter < $rowCount; $counter++){
$form['userBoxArea'][$counter] = [
'userBox' => [
'#type' => 'container',
'nameBox' => [
'#type' => 'container',
'firstName' => [
'#type' => 'textfield',
'#title' => 'Enter your first name',
],
],
'save' => [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#name' => 'save-' . $counter,
'#submit' => ['::submitForm'],
'#validate' => ['::validateForm'],
'#limit_validation_errors' => [],
],
],
];
}
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$firstName = $form_state->getValue('firstName');
if (strlen($firstName) == NULL) {
$form_state->setErrorByName('firstName', $this->t('The First Name should not be empty.'));
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$submitString = $form_state->getTriggeringElement()['#name'];
$submitNumber = explode("-", $submitString);
$count = $submitNumber[1];
$firstName = $form_state->getValue('userBoxArea')[$count]['userBox']['nameBox']['firstName'];
$this->messenger()->addMessage($this->t('Your first name is %firstName has been saved.', ['%firstName' => $firstName]));
$this->messenger()->addMessage($this->t('Button number: @num', ['@num' => $count]));
}
The rowCount pertains to the row in my database. The process is to acquire firstName from the user and those variables will be saved inside the database.
I have researched articles from Drupal if there is a limitation of the #tree containers and found nothing about it.
Any suggestions if I am missing something. How do you retrieve the value of "firstName"?
Thanks in advance.