questionnaires-8.x-1.x-dev/src/Plugin/Field/FieldWidget/MultiChoiceWidget.php
src/Plugin/Field/FieldWidget/MultiChoiceWidget.php
<?php
namespace Drupal\questionnaires\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\Validator\ConstraintViolationInterface;
/**
* Plugin implementation of the 'multi_choice_widget' widget.
*
* @FieldWidget(
* id = "multi_choice_widget",
* module = "questionnaires",
* label = @Translation("Multi choice widget"),
* field_types = {
* "multi_choice_field"
* }
* )
*/
class MultiChoiceWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'rows' => '5',
'placeholder' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = [];
$elements['rows'] = array(
'#type' => 'number',
'#title' => t('Rows'),
'#default_value' => $this->getSetting('rows'),
'#required' => TRUE,
'#min' => 1,
);
$elements['placeholder'] = array(
'#type' => 'textfield',
'#title' => t('Placeholder'),
'#default_value' => $this->getSetting('placeholder'),
'#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
);
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = t('Number of rows: @rows', array(
'@rows' => $this->getSetting('rows'),
));
$placeholder = $this->getSetting('placeholder');
if (!empty($placeholder)) {
$summary[] = t('Placeholder: @placeholder', array(
'@placeholder' => $placeholder,
));
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = $element + array(
'#type' => 'text_format',
'#base_type' => 'textarea',
'#format' => $items[$delta]->format,
'#default_value' => $items[$delta]->value,
'#rows' => $this->getSetting('rows'),
'#placeholder' => $this->getSetting('placeholder'),
'#attributes' => array(
'class' => array(
'js-text-full',
'text-full',
),
),
);
$element['correct_answer'] = array(
'#type' => 'checkbox',
'#default_value' => !empty($items[$delta]->correct_answer),
'#title' => t('Correct answer'),
);
return $element;
}
/**
* {@inheritdoc}
*/
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
if ($violation->arrayPropertyPath == array(
'format',
) && isset($element['format']['#access']) && !$element['format']['#access']) {
return FALSE;
}
return $element;
}
}
