You are here

public function TableConfigForm::buildForm in Data 8

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides EntityForm::buildForm

File

src/Form/TableConfigForm.php, line 20

Class

TableConfigForm
Class TableConfigForm.

Namespace

Drupal\data\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  $data_table_config = $this->entity;
  if ($data_table_config
    ->isNew()) {
    $number_of_fields = $form_state
      ->getValue('field_num');
    $this->step = $number_of_fields ? 1 : 0;
  }
  else {
    $number_of_fields = count($data_table_config->table_schema);
    $this->step = 1;
  }

  // Multistep form.
  if (!$this->step) {

    // First form, ask for the database table name.
    $form['title'] = array(
      '#type' => 'textfield',
      '#title' => $this
        ->t('Table title'),
      '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
      '#default_value' => $data_table_config
        ->label(),
      '#description' => $this
        ->t('Table title.'),
      '#required' => TRUE,
    );
    $form['id'] = array(
      '#type' => 'machine_name',
      '#default_value' => $data_table_config
        ->id(),
      '#machine_name' => array(
        'exists' => '\\Drupal\\data\\Entity\\TableConfig::load',
        'source' => array(
          'title',
        ),
      ),
      '#description' => $this
        ->t('Machine readable name of the table - e. g. "my_table". Must only contain lower case letters and _.'),
      '#disabled' => !$data_table_config
        ->isNew(),
    );
    $form['field_num'] = array(
      '#type' => 'textfield',
      '#title' => t('Number of fields'),
      '#description' => t('The number of fields this table should contain.'),
      '#default_value' => 1,
      '#required' => TRUE,
    );
    $form['actions']['submit']['#value'] = t('Next');
  }
  else {

    // Second form, ask for the database field names.
    $form['help']['#markup'] = t('Define the fields of the new table.');
    $form['table_schema'] = array(
      '#type' => 'table',
      '#header' => array(
        t('Name'),
        t('Label'),
        t('Type'),
        t('Size'),
        t('Length'),
        t('Unsigned'),
        t('Index'),
        t('Primary key'),
      ),
    );
    for ($i = 0; $i < $number_of_fields; $i++) {
      $form['table_schema'][$i] = $this
        ->fieldForm($i, TRUE);
    }
    $form['actions']['submit']['#value'] = $this->entity
      ->isNew() ? t('Create') : t('Update');
  }
  return $form;
}