Score:0

How to retrieve #tree values inside multiple containers?

cn flag

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.

Jaypan avatar
de flag
You need to show more code, there isn't enough there to debug. More of the submission handler - where is $counter being etc. What are you using to determine the value is empty?
Jeirod avatar
cn flag
@Jaypan Sorry about that, I have updated my code. In determining if the value is empty, I am using the function of validateForm. I was wondering how I can't access the textfield inside of multiple containers.
Jeirod avatar
cn flag
The error I am receiving is "Undefined index: nameBox" even though it is present.
Score:0
de flag

The error comes from validateForm(), where you use the following line.

$firstName = $form_state->getValue('firstName');

You need to retrieve the first name values using the tree.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.