VoteUpDownField.php in Vote Up/Down 8
File
src/Plugin/Field/FieldType/VoteUpDownField.php
View source
<?php
namespace Drupal\vud\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
class VoteUpDownField extends FieldItemBase {
public static function defaultStorageSettings() {
return [
'widget' => '',
] + parent::defaultStorageSettings();
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Widget Template'))
->setSetting('case_sensitive', $field_definition
->getSetting('case_sensitive'))
->setRequired(TRUE);
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$schema = [
'columns' => [
'value' => [
'type' => $field_definition
->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
'length' => (int) $field_definition
->getSetting('max_length'),
'binary' => $field_definition
->getSetting('case_sensitive'),
],
],
];
return $schema;
}
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element = [];
$widgets = \Drupal::service('plugin.manager.vud')
->getDefinitions();
$widgets_options = [];
foreach ($widgets as $vote_plugin) {
$widgets_options[$vote_plugin['id']] = $vote_plugin['admin_label'];
}
$element['widget'] = [
'#type' => 'select',
'#title' => $this
->t('Vote Up/Down widget'),
'#options' => $widgets_options,
'#required' => TRUE,
'#default_value' => $this
->getSetting('widget'),
'#disabled' => $has_data,
];
return $element;
}
public function getConstraints() {
$constraints = parent::getConstraints();
if ($max_length = $this
->getSetting('max_length')) {
$constraint_manager = \Drupal::typedDataManager()
->getValidationConstraintManager();
$constraints[] = $constraint_manager
->create('ComplexData', [
'value' => [
'Length' => [
'max' => $max_length,
'maxMessage' => $this
->t('%name: may not be longer than @max characters.', [
'%name' => $this
->getFieldDefinition()
->getLabel(),
'@max' => $max_length,
]),
],
],
]);
}
return $constraints;
}
public function isEmpty() {
$value = $this
->get('value')
->getValue();
return $value === NULL || $value === '';
}
}