View source
<?php
namespace Drupal\webform\Plugin\WebformElement;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Element\WebformRating as WebformRatingElement;
use Drupal\webform\WebformInterface;
use Drupal\webform\WebformSubmissionInterface;
class WebformRating extends Range {
protected function defineDefaultProperties() {
$properties = [
'max' => 5,
'default_value' => 0,
'star_size' => 'medium',
'reset' => FALSE,
] + parent::defineDefaultProperties();
unset($properties['output'], $properties['output__field_prefix'], $properties['output__field_suffix'], $properties['output__attributes']);
return $properties;
}
public function getTestValues(array $element, WebformInterface $webform, array $options = []) {
$element += [
'#min' => 0,
'#max' => 5,
];
return parent::getTestValues($element, $webform, $options);
}
protected function formatHtmlItem(array $element, WebformSubmissionInterface $webform_submission, array $options = []) {
$value = $this
->getValue($element, $webform_submission, $options);
$format = $this
->getItemFormat($element);
switch ($format) {
case 'star':
if (!empty($options['email']) || !empty($options['pdf'])) {
return parent::formatTextItem($element, $webform_submission, $options);
}
$build = [
'#value' => $value,
'#readonly' => TRUE,
] + $element;
return WebformRatingElement::buildRateIt($build);
default:
return parent::formatHtmlItem($element, $webform_submission, $options);
}
}
public function getItemDefaultFormat() {
return 'star';
}
public function getItemFormats() {
return parent::getItemFormats() + [
'star' => $this
->t('Star'),
];
}
public function preview() {
return [
'#type' => $this
->getTypeName(),
'#title' => $this
->getPluginLabel(),
];
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['number']['#title'] = $this
->t('Rating settings');
$form['number']['star_size'] = [
'#type' => 'select',
'#title' => $this
->t('Star 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,
];
$form['number']['reset'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Show reset button'),
'#description' => $this
->t('If checked, a reset button will be placed before the rating element.'),
'#return_value' => TRUE,
];
$form['validation']['required_container']['#states'] = [
'visible' => [
':input[name="properties[min]"]' => [
'value' => '0',
],
],
];
return $form;
}
}