datafield-1.x-dev/src/Plugin/DataField/FieldType/BooleanItem.php
src/Plugin/DataField/FieldType/BooleanItem.php
<?php
namespace Drupal\datafield\Plugin\DataField\FieldType;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\datafield\Attribute\DataFieldType;
use Drupal\datafield\Plugin\DataFieldTypeInterface;
/**
* Defines the 'boolean' entity field type.
*/
#[DataFieldType(
id: 'boolean',
label: new TranslatableMarkup('Boolean'),
description: new TranslatableMarkup('An data field containing a boolean value.'),
default_widget: 'checkbox',
default_formatter: 'boolean',
)]
class BooleanItem implements DataFieldTypeInterface {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return [
'type' => 'int',
'size' => 'tiny',
];
}
/**
* {@inheritdoc}
*/
public static function schema(array $settings) {
$default = self::defaultStorageSettings();
return [
'columns' => [
'value' => $default,
],
];
}
/**
* {@inheritdoc}
*/
public function getPossibleValues(?AccountInterface $account = NULL) {
return [0, 1];
}
/**
* {@inheritdoc}
*/
public function getSettableValues(?AccountInterface $account = NULL) {
return [0, 1];
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue() {
return mt_rand(0, 1);
}
/**
* {@inheritdoc}
*/
public function getPluginId() {
return '';
}
/**
* {@inheritdoc}
*/
public function getPluginDefinition() {
return [];
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(array $settings) {
$name = $settings['name'];
$data_type = $settings['type'] ?? 'boolean';
return DataDefinition::create($data_type)
->setLabel(new TranslatableMarkup('%name value', ['%name' => $name]))
->setRequired(FALSE);
}
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->t('Boolean');
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $field_settings, array $settings) {
$field_form = [
'label' => [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#default_value' => $field_settings['label'] ?? ucfirst($settings["name"]),
],
'required' => [
'#type' => 'checkbox',
'#title' => $this->t('Required'),
'#default_value' => $field_settings['required'] ?? FALSE,
],
'on_label' => [
'#type' => 'textfield',
'#title' => $this->t('"On" label'),
'#default_value' => $field_settings['on_label'] ?? '',
],
'off_label' => [
'#type' => 'textfield',
'#title' => $this->t('"Off" label'),
'#default_value' => $field_settings['off_label'] ?? '',
],
];
return $field_form;
}
/**
* {@inheritDoc}
*/
public function getConstraints(array $settings) {
$constraints = [];
if ($settings['required']) {
$constraints['NotEqualTo']['value'] = 0;
$constraints['NotEqualTo']['message'] = $this->t('This value should not be blank.');
}
return $constraints;
}
}
