You are here

public function FormWidgetExampleForm::buildForm in Typed Data API enhancements 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 FormInterface::buildForm

File

tests/modules/typed_data_widget_test/src/FormWidgetExampleForm.php, line 105

Class

FormWidgetExampleForm
Class FormWidgetExampleForm.

Namespace

Drupal\typed_data_widget_test

Code

public function buildForm(array $form, FormStateInterface $form_state, $widget_id = NULL) {
  $widget = $this
    ->getFormWidgetManager()
    ->createInstance($widget_id);

  // Read and write widget configuration from the state.
  // Allow tests to define a custom context definition.
  $context_definition = $this->state
    ->get('typed_data_widgets.definition');
  $context_definition = $context_definition ?: $this
    ->getExampleContextDefinition($widget_id);
  $form_state
    ->set('widget_id', $widget_id);
  $form_state
    ->set('context_definition', $context_definition);

  // Create a typed data object.
  $data = $this
    ->getTypedDataManager()
    ->create($context_definition
    ->getDataDefinition());
  $value = $this->state
    ->get('typed_data_widgets.' . $widget_id);
  $value = isset($value) ? $value : $context_definition
    ->getDefaultValue();
  $data
    ->setValue($value);
  $subform_state = SubformState::createWithParents([
    'data',
  ], $form, $form_state);
  $form['data'] = $widget
    ->form($data, $subform_state);
  $form['actions']['#type'] = 'actions';

  // 'Submit' will save the widget value.
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => 'Submit',
  ];

  // 'Reset' will erase the saved value and revert to default.
  $form['actions']['reset'] = [
    '#type' => 'submit',
    '#value' => 'Reset',
  ];
  return $form;
}