View source
<?php
namespace Drupal\faqfield\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
class FaqFieldItem extends FieldItemBase {
public static function defaultFieldSettings() {
return [
'default_format' => 'plain_text',
] + parent::defaultFieldSettings();
}
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = [];
$properties['question'] = DataDefinition::create('string')
->setLabel(t('Question value'));
$properties['answer'] = DataDefinition::create('string')
->setLabel(t('Answer value'));
$properties['answer_format'] = DataDefinition::create('string')
->setLabel(t('Answer text format'));
return $properties;
}
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'question' => [
'description' => 'The FAQ Field question values.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
],
'answer' => [
'description' => 'The FAQ Field answer values.',
'type' => 'text',
'not null' => TRUE,
'size' => 'medium',
],
'answer_format' => [
'description' => 'The FAQ Field answer format.',
'type' => 'varchar',
'length' => 255,
'not null' => FALSE,
],
],
];
}
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$formats = filter_formats();
$filter_options = [];
foreach ($formats as $format) {
$filter_options[$format
->get('format')] = $format
->get('name');
}
$element['default_format'] = [
'#type' => 'select',
'#title' => $this
->t('Default text format'),
'#default_value' => $this
->getSetting('default_format'),
'#options' => $filter_options,
'#access' => count($formats) > 1,
'#required' => TRUE,
'#description' => $this
->t('Default text format to filter FAQ field answer content.'),
];
return $element;
}
public function isEmpty() {
$answer = $this
->get('answer')
->getValue();
$question = $this
->get('question')
->getValue();
$answer_value = is_array($answer) ? $answer['value'] : $answer;
return empty($question) && empty($answer_value);
}
public static function mainPropertyName() {
return 'question';
}
public function setValue($values, $notify = TRUE) {
if (is_array($values) && isset($values['answer']) && is_array($values['answer'])) {
$values['answer_format'] = $values['answer']['format'];
$values['answer'] = $values['answer']['value'];
}
parent::setValue($values, $notify);
}
}