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 array(
'test_widget_setting' => 'dummy test string',
'role' => 'anonymous',
'role2' => 'anonymous',
) + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting'] = array(
'#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 = array();
$summary[] = t('@setting: @value', array(
'@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 += array(
'#type' => 'textfield',
'#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : '',
);
return array(
'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;
}
}