class FormWidgetExampleForm in Typed Data API enhancements 8
Class FormWidgetExampleForm.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\typed_data_widget_test\FormWidgetExampleForm uses TypedDataTrait, FormWidgetManagerTrait
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_testView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
FormWidgetExampleForm:: |
protected | property | The state storage. | |
FormWidgetExampleForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
|
FormWidgetExampleForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
FormWidgetExampleForm:: |
public | function | Gets some example context definition. | |
FormWidgetExampleForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
|
FormWidgetExampleForm:: |
public | function |
Form submission handler. Overrides FormInterface:: |
|
FormWidgetExampleForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
FormWidgetExampleForm:: |
public | function | Form constructor. | |
FormWidgetManagerTrait:: |
protected | property | The widget manager. | |
FormWidgetManagerTrait:: |
public | function | Gets the widget manager. | |
FormWidgetManagerTrait:: |
public | function | Sets the widget manager. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
TypedDataTrait:: |
protected | property | The typed data manager used for creating the data types. | |
TypedDataTrait:: |
public | function | Gets the typed data manager. | 2 |
TypedDataTrait:: |
public | function | Sets the typed data manager. | 2 |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |