BooleanItem.php in Drupal 8
File
core/lib/Drupal/Core/Field/Plugin/Field/FieldType/BooleanItem.php
View source
<?php
namespace Drupal\Core\Field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\OptionsProviderInterface;
use Drupal\Core\TypedData\DataDefinition;
class BooleanItem extends FieldItemBase implements OptionsProviderInterface {
public static function defaultFieldSettings() {
return [
'on_label' => new TranslatableMarkup('On'),
'off_label' => new TranslatableMarkup('Off'),
] + parent::defaultFieldSettings();
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('boolean')
->setLabel(t('Boolean value'))
->setRequired(TRUE);
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'int',
'size' => 'tiny',
],
],
];
}
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$element['on_label'] = [
'#type' => 'textfield',
'#title' => $this
->t('"On" label'),
'#default_value' => $this
->getSetting('on_label'),
'#required' => TRUE,
];
$element['off_label'] = [
'#type' => 'textfield',
'#title' => $this
->t('"Off" label'),
'#default_value' => $this
->getSetting('off_label'),
'#required' => TRUE,
];
return $element;
}
public function getPossibleValues(AccountInterface $account = NULL) {
return [
0,
1,
];
}
public function getPossibleOptions(AccountInterface $account = NULL) {
return [
0 => $this
->getSetting('off_label'),
1 => $this
->getSetting('on_label'),
];
}
public function getSettableValues(AccountInterface $account = NULL) {
return [
0,
1,
];
}
public function getSettableOptions(AccountInterface $account = NULL) {
return $this
->getPossibleOptions($account);
}
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$values['value'] = mt_rand(0, 1);
return $values;
}
}