eav_field-2.x-dev/src/Form/EavAttributeValueWidgetSettingsForm.php
src/Form/EavAttributeValueWidgetSettingsForm.php
<?php
namespace Drupal\eav_field\Form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\WidgetPluginManager;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\eav_field\Entity\EavAttributeInterface;
class EavAttributeValueWidgetSettingsForm extends FormBase {
/**
* {@inheritDoc}
*/
public function getFormId(): string {
return 'eav_attribute_value_widget_settings_form';
}
/**
* {@inheritDoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, EavAttributeInterface $eav_attribute = NULL): array {
$form['#title'] = $this->t('Widget settings of attribute "@attribute"', ['@attribute' => $eav_attribute->getAdministrativeLabel()]);
$field_definition = $eav_attribute->configureValueFieldDefinition();
$widget_manager = \Drupal::service('plugin.manager.field.widget'); /** @var WidgetPluginManager $widget_manager */
$widget = $widget_manager->getInstance([
'field_definition' => $field_definition,
'configuration' => [
'type' => $eav_attribute->getValueWidgetType(),
'settings' => $eav_attribute->getValueWidgetSettings(),
],
]);
$form['widget_settings'] = [
'#tree' => TRUE,
'#parents' => ['fields', $eav_attribute->getValueFieldName(), 'settings_edit_form', 'settings'],
];
if ($widget_settings_form = $widget->settingsForm($form, $form_state)) {
$form['widget_settings'] += $widget_settings_form;
}
else {
$form['widget_settings']['#markup'] = $this->t('No settings.');
}
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#button_type' => 'primary',
];
return $form;
}
/**
* {@inheritDoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$widget_settings = NestedArray::getValue($form_state->getValues(), $form['widget_settings']['#parents']);
$attribute = $form_state->getBuildInfo()['args'][0]; /** @var EavAttributeInterface $attribute */
$attribute->set('value_widget_settings', $widget_settings);
$attribute->save();
// Redirect to next step
if ($this->getRequest()->query->get('operation') == 'add') {
$form_state->setRedirect('entity.eav_attribute.value_formatter_form', ['eav_attribute' => $attribute->id()], ['query' => ['operation' => 'add']]);
}
else {
$this->messenger()->addMessage($this->t('Widget settings saved.'));
}
}
}
