View source
<?php
namespace Drupal\webform\Plugin\WebformElement;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Element\WebformHtmlEditor;
use Drupal\webform\Plugin\WebformElementBase;
use Drupal\webform\WebformSubmissionInterface;
class Color extends WebformElementBase {
protected function defineDefaultProperties() {
$properties = [
'color_size' => 'medium',
] + parent::defineDefaultProperties();
unset($properties['format_items'], $properties['format_items_html'], $properties['format_items_text']);
return $properties;
}
public function prepare(array &$element, WebformSubmissionInterface $webform_submission = NULL) {
parent::prepare($element, $webform_submission);
$color_size = isset($element['#color_size']) ? $element['#color_size'] : 'medium';
$element['#attributes']['class'][] = 'form-color-' . $color_size;
$element['#attributes'] += [
'title' => $this
->t('Hexadecimal color'),
'pattern' => '#[a-f0-9]{6}',
'placeholder' => '#000000',
];
$element['#attached']['library'][] = 'webform/webform.element.color';
}
protected function formatHtmlItem(array $element, WebformSubmissionInterface $webform_submission, array $options = []) {
$value = $this
->getValue($element, $webform_submission, $options);
if (empty($value)) {
return '';
}
$format = $this
->getItemFormat($element);
switch ($format) {
case 'swatch':
if (!in_array('font', WebformHtmlEditor::getAllowedTags())) {
return $value;
}
else {
return [
'#type' => 'inline_template',
'#template' => '<font color="{{ value }}">█</font> {{ value }}',
'#context' => [
'value' => $value,
],
];
}
default:
return parent::formatHtmlItem($element, $webform_submission, $options);
}
}
public function getItemDefaultFormat() {
return 'swatch';
}
public function getItemFormats() {
return parent::getItemFormats() + [
'swatch' => $this
->t('Color swatch'),
];
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['color'] = [
'#type' => 'fieldset',
'#title' => $this
->t('Color settings'),
];
$form['color']['color_size'] = [
'#type' => 'select',
'#title' => $this
->t('Color swatch size'),
'#options' => [
'small' => $this
->t('Small (@size)', [
'@size' => '16px',
]),
'medium' => $this
->t('Medium (@size)', [
'@size' => '24px',
]),
'large' => $this
->t('Large (@size)', [
'@size' => '32px',
]),
],
'#required' => TRUE,
];
return $form;
}
}