function DbtngExampleUpdateForm::buildForm

Same name in other branches
  1. 3.x modules/dbtng_example/src/Form/DbtngExampleUpdateForm.php \Drupal\dbtng_example\Form\DbtngExampleUpdateForm::buildForm()

Sample UI to update a record.

Overrides FormInterface::buildForm

File

modules/dbtng_example/src/Form/DbtngExampleUpdateForm.php, line 51

Class

DbtngExampleUpdateForm
Sample UI to update a record.

Namespace

Drupal\dbtng_example\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
    // Wrap the form in a div.
    $form = [
        '#prefix' => '<div id="updateform">',
        '#suffix' => '</div>',
    ];
    // Add some explanatory text to the form.
    $form['message'] = [
        '#markup' => $this->t('Demonstrates a database update operation.'),
    ];
    // Query for items to display.
    $entries = $this->repository
        ->load();
    // Tell the user if there is nothing to display.
    if (empty($entries)) {
        $form['no_values'] = [
            '#value' => $this->t('No entries exist in the table dbtng_example table.'),
        ];
        return $form;
    }
    $keyed_entries = [];
    $options = [];
    foreach ($entries as $entry) {
        $options[$entry->pid] = $this->t('@pid: @name @surname (@age)', [
            '@pid' => $entry->pid,
            '@name' => $entry->name,
            '@surname' => $entry->surname,
            '@age' => $entry->age,
        ]);
        $keyed_entries[$entry->pid] = $entry;
    }
    // Grab the pid.
    $pid = $form_state->getValue('pid');
    // Use the pid to set the default entry for updating.
    $default_entry = !empty($pid) ? $keyed_entries[$pid] : $entries[0];
    // Save the entries into the $form_state. We do this so the AJAX callback
    // doesn't need to repeat the query.
    $form_state->setValue('entries', $keyed_entries);
    $form['pid'] = [
        '#type' => 'select',
        '#options' => $options,
        '#title' => $this->t('Choose entry to update'),
        '#default_value' => $default_entry->pid,
        '#ajax' => [
            'wrapper' => 'updateform',
            'callback' => [
                $this,
                'updateCallback',
            ],
        ],
    ];
    $form['name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Updated first name'),
        '#size' => 15,
        '#default_value' => $default_entry->name,
    ];
    $form['surname'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Updated last name'),
        '#size' => 15,
        '#default_value' => $default_entry->surname,
    ];
    $form['age'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Updated age'),
        '#size' => 4,
        '#default_value' => $default_entry->age,
        '#description' => $this->t('Values greater than 127 will cause an exception'),
    ];
    $form['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Update'),
    ];
    return $form;
}