View source
<?php
namespace Drupal\field_test\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
class TestFieldWidget extends WidgetBase {
public static function defaultSettings() {
return [
'test_widget_setting' => 'dummy test string',
'role' => 'anonymous',
'role2' => 'anonymous',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field widget setting'),
'#description' => t('A dummy form element to simulate field widget setting.'),
'#default_value' => $this
->getSetting('test_widget_setting'),
'#required' => FALSE,
];
return $element;
}
public function settingsSummary() {
$summary = [];
$summary[] = t('@setting: @value', [
'@setting' => 'test_widget_setting',
'@value' => $this
->getSetting('test_widget_setting'),
]);
return $summary;
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element += [
'#type' => 'textfield',
'#default_value' => $items[$delta]->value ?? '',
];
return [
'value' => $element,
];
}
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
return $element['value'];
}
public function calculateDependencies() {
$dependencies = parent::calculateDependencies();
foreach ([
'role',
'role2',
] as $setting) {
if (!empty($role_id = $this
->getSetting($setting))) {
$dependencies['config'][] = "user.role.{$role_id}";
}
}
return $dependencies;
}
public function onDependencyRemoval(array $dependencies) {
$changed = parent::onDependencyRemoval($dependencies);
if (!empty($role_id = $this
->getSetting('role'))) {
if (!empty($dependencies['config']["user.role.{$role_id}"])) {
$this
->setSetting('role', 'anonymous');
$changed = TRUE;
}
}
return $changed;
}
}