YamlFormTableTrait.php in YAML Form 8
File
src/Plugin/YamlFormElement/YamlFormTableTrait.php
View source
<?php
namespace Drupal\yamlform\Plugin\YamlFormElement;
use Drupal\Core\Form\FormStateInterface;
use Drupal\yamlform\YamlFormSubmissionInterface;
trait YamlFormTableTrait {
public function prepare(array &$element, YamlFormSubmissionInterface $yamlform_submission) {
parent::prepare($element, $yamlform_submission);
$element['#attributes']['class'][] = str_replace('_', '-', $element['#type']);
if (!isset($element['#header'])) {
$element['#header'] = [
isset($element['#title']) ? $element['#title'] : '',
];
}
if (isset($element['#options'])) {
foreach ($element['#options'] as $options_key => $options_value) {
if (is_string($options_value)) {
$element['#options'][$options_key] = [
[
'value' => $options_value,
],
];
}
}
}
if ($this
->hasMultipleValues($element)) {
$element['#element_validate'][] = [
get_class($this),
'validateMultipleOptions',
];
}
$element['#attached']['library'][] = 'yamlform/yamlform.element.' . $element['#type'];
}
public function setDefaultValue(array &$element) {
if (isset($element['#default_value']) && is_array($element['#default_value'])) {
$element['#default_value'] = array_combine($element['#default_value'], $element['#default_value']);
}
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['options']['js_select'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Select all'),
'#description' => $this
->t('If checked, a select all checkbox will be added to the header.'),
'#return_value' => TRUE,
];
return $form;
}
protected function getTableSelectElementSelectorOptions(array $element, $input_selector = '') {
$title = $this
->getAdminLabel($element) . ' [' . $this
->getPluginLabel() . ']';
$name = $element['#yamlform_key'];
$type = $this
->hasMultipleValues($element) ? $this
->t('Checkbox') : $this
->t('Radio');
$selectors = [];
foreach ($element['#options'] as $value => $text) {
if (is_array($text)) {
$text = $value;
}
$selectors[":input[name=\"{$name}[{$value}]{$input_selector}\"]"] = $text . ' [' . $type . ']';
}
return [
$title => $selectors,
];
}
}