function SystemStateEdit::buildForm

Same name and namespace in other branches
  1. 5.x src/Form/SystemStateEdit.php \Drupal\devel\Form\SystemStateEdit::buildForm()

Overrides FormInterface::buildForm

File

src/Form/SystemStateEdit.php, line 54

Class

SystemStateEdit
Form API form to edit a state.

Namespace

Drupal\devel\Form

Code

public function buildForm(array $form, FormStateInterface $form_state, $state_name = '') {
    // Get the old value.
    $old_value = $this->state
        ->get($state_name);
    if (!isset($old_value)) {
        $this->messenger()
            ->addWarning($this->t('State @name does not exist in the system.', [
            '@name' => $state_name,
        ]));
        return;
    }
    // Only simple structures are allowed to be edited.
    $disabled = !$this->checkObject($old_value);
    if ($disabled) {
        $this->messenger()
            ->addWarning($this->t('Only simple structures are allowed to be edited. State @name contains objects.', [
            '@name' => $state_name,
        ]));
    }
    // First we show the user the content of the variable about to be edited.
    $form['value'] = [
        '#type' => 'item',
        '#title' => $this->t('Current value for %name', [
            '%name' => $state_name,
        ]),
        // phpcs:ignore Drupal.Functions.DiscouragedFunctions
'#markup' => kpr($old_value, TRUE),
    ];
    $transport = 'plain';
    if (!$disabled && is_array($old_value)) {
        try {
            $old_value = Yaml::encode($old_value);
            $transport = 'yaml';
        } catch (InvalidDataTypeException $e) {
            $this->messenger()
                ->addError($this->t('Invalid data detected for @name : %error', [
                '@name' => $state_name,
                '%error' => $e->getMessage(),
            ]));
            return;
        }
    }
    // Store in the form the name of the state variable.
    $form['state_name'] = [
        '#type' => 'value',
        '#value' => $state_name,
    ];
    // Set the transport format for the new value. Values:
    // - plain
    // - yaml.
    $form['transport'] = [
        '#type' => 'value',
        '#value' => $transport,
    ];
    $form['new_value'] = [
        '#type' => 'textarea',
        '#title' => $this->t('New value'),
        '#default_value' => $disabled ? '' : $old_value,
        '#disabled' => $disabled,
        '#rows' => 15,
    ];
    $form['actions'] = [
        '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Save'),
        '#disabled' => $disabled,
    ];
    $form['actions']['cancel'] = [
        '#type' => 'link',
        '#title' => $this->t('Cancel'),
        '#url' => Url::fromRoute('devel.state_system_page'),
    ];
    return $form;
}