eav_field-2.x-dev/src/Form/EavAttributeValueFormatterSettingsForm.php
src/Form/EavAttributeValueFormatterSettingsForm.php
<?php
namespace Drupal\eav_field\Form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FormatterPluginManager;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\eav_field\Entity\EavAttributeInterface;
class EavAttributeValueFormatterSettingsForm extends FormBase {
/**
* {@inheritDoc}
*/
public function getFormId(): string {
return 'eav_attribute_value_formatter_settings_form';
}
/**
* {@inheritDoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, EavAttributeInterface $eav_attribute = NULL): array {
$form['#title'] = $this->t('Formatter settings of attribute "@attribute"', ['@attribute' => $eav_attribute->getAdministrativeLabel()]);
if ($eav_attribute->getValueFormatterType()) {
$field_definition = $eav_attribute->configureValueFieldDefinition();
$formatter_manager = \Drupal::service('plugin.manager.field.formatter'); /** @var FormatterPluginManager $formatter_manager */
$formater = $formatter_manager->getInstance([
'field_definition' => $field_definition,
'view_mode' => 'full',
'configuration' => [
'type' => $eav_attribute->getValueFormatterType(),
'settings' => $eav_attribute->getValueFormatterSettings(),
],
]);
if ($formatter_settings_form = $formater->settingsForm($form, $form_state)) {
$form['formatter_settings'] = [
'#tree' => TRUE,
'#parents' => ['fields', $eav_attribute->getValueFieldName(), 'settings_edit_form', 'settings'],
];
$form['formatter_settings'] += $formatter_settings_form;
}
}
if (!isset($form['formatter_settings'])) {
$form['empty'] = [
'#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 {
$attribute = $form_state->getBuildInfo()['args'][0]; /** @var EavAttributeInterface $attribute */
if (isset($form['formatter_settings'])) {
$formatter_settings = NestedArray::getValue($form_state->getValues(), $form['formatter_settings']['#parents']);
$attribute->set('value_formatter_settings', $formatter_settings);
$attribute->save();
}
// Redirect to attributes list
if ($this->getRequest()->query->get('operation') == 'add') {
$this->messenger()->addMessage($this->t('Attribute "@attribute" added.', ['@attribute' => $attribute->label()]));
$form_state->setRedirect('entity.eav_attribute.collection');
}
else {
$this->messenger()->addMessage($this->t('Formatter settings saved.'));
}
}
}
