You are here

class FormWidgetExampleForm in Typed Data API enhancements 8

Class FormWidgetExampleForm.

Hierarchy

Expanded class hierarchy of FormWidgetExampleForm

1 string reference to 'FormWidgetExampleForm'
typed_data_widget_test.routing.yml in tests/modules/typed_data_widget_test/typed_data_widget_test.routing.yml
tests/modules/typed_data_widget_test/typed_data_widget_test.routing.yml

File

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

Namespace

Drupal\typed_data_widget_test
View source
class FormWidgetExampleForm extends FormBase {
  use FormWidgetManagerTrait;
  use TypedDataTrait;

  /**
   * The state storage.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * Form constructor.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state storage.
   */
  public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('state'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'typed_data_widget_test_form';
  }

  /**
   * Gets some example context definition.
   *
   * @param string $widget_id
   *   The widget id.
   *
   * @return \Drupal\Core\Plugin\Context\ContextDefinitionInterface
   *   The definition.
   */
  public function getExampleContextDefinition($widget_id) {
    switch ($widget_id) {
      default:
      case 'text_input':
        return ContextDefinition::create('string')
          ->setLabel('Example string')
          ->setDescription('Some example string with max. 8 characters.')
          ->setDefaultValue('default')
          ->addConstraint('Length', [
          'max' => 8,
        ]);
      case 'textarea':
        return ContextDefinition::create('text')
          ->setLabel('Example text area')
          ->setDefaultValue("default line one\nline two")
          ->setDescription('This is the long textarea example description.');
      case 'select':
        return ContextDefinition::create('filter_format')
          ->setLabel('Filter format')
          ->setDescription('Some example selection.');
      case 'datetime':
        return ContextDefinition::create('datetime_iso8601')
          ->setLabel('Example datetime')
          ->setDescription('Some example datetime.');
      case 'datetime_range':
        return ContextDefinition::create('any')
          ->setLabel('Example datetime range')
          ->setDescription('Some example datetime range.');
      case 'broken':
        return ContextDefinition::create('string')
          ->setLabel('Example string');
    }
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $context_definition = $form_state
      ->get('context_definition');
    $widget_id = $form_state
      ->get('widget_id');
    $widget = $this
      ->getFormWidgetManager()
      ->createInstance($widget_id);
    $subform_state = SubformState::createWithParents([
      'data',
    ], $form, $form_state);
    $data = $this
      ->getTypedDataManager()
      ->create($context_definition
      ->getDataDefinition());
    $widget
      ->extractFormValues($data, $subform_state);

    // Validate the data and flag possible violations.
    $violations = $data
      ->validate();
    $widget
      ->flagViolations($data, $violations, $subform_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $context_definition = $form_state
      ->get('context_definition');
    $widget_id = $form_state
      ->get('widget_id');
    $widget = $this
      ->getFormWidgetManager()
      ->createInstance($widget_id);
    if (($triggering_element = $form_state
      ->getTriggeringElement()) && $triggering_element['#id'] == 'edit-reset') {

      // Erase the widget data.
      $this->state
        ->set('typed_data_widgets.' . $widget_id, NULL);
      $this
        ->messenger()
        ->addMessage($this
        ->t('Value reset to default'));
    }
    else {
      $subform_state = SubformState::createWithParents([
        'data',
      ], $form, $form_state);
      $data = $this
        ->getTypedDataManager()
        ->create($context_definition
        ->getDataDefinition());
      $widget
        ->extractFormValues($data, $subform_state);

      // Read and write widget configuration via the state.
      $this->state
        ->set('typed_data_widgets.' . $widget_id, $data
        ->getValue());

      // Display the value saved. Use print_r in case the value is an array.
      $this
        ->messenger()
        ->addMessage($this
        ->t('Value saved: %value', [
        '%value' => print_r($data
          ->getValue(), TRUE),
      ]));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormWidgetExampleForm::$state protected property The state storage.
FormWidgetExampleForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
FormWidgetExampleForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FormWidgetExampleForm::getExampleContextDefinition public function Gets some example context definition.
FormWidgetExampleForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FormWidgetExampleForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FormWidgetExampleForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FormWidgetExampleForm::__construct public function Form constructor.
FormWidgetManagerTrait::$widgetManager protected property The widget manager.
FormWidgetManagerTrait::getFormWidgetManager public function Gets the widget manager.
FormWidgetManagerTrait::setFormWidgetManager public function Sets the widget manager.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.