View source
<?php
namespace Drupal\views_fields_on_off\Plugin\views\field;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\Core\Form\FormStateInterface;
class ViewsFieldsOnOffForm extends FieldPluginBase {
public function canExpose() {
return TRUE;
}
public function isExposed() {
return TRUE;
}
public function buildExposedForm(&$form, FormStateInterface $form_state) {
$field_id = $this->options['id'];
$label = $this->options['label'];
$selected_options = $this->options['fields'];
$all_fields = $this->displayHandler
->getFieldLabels();
$options = array_filter($all_fields, function ($key) use ($selected_options) {
return in_array($key, $selected_options, TRUE);
}, ARRAY_FILTER_USE_KEY);
$form[$field_id] = [
'#type' => $this->options['exposed_select_type'],
'#title' => $this
->t('@value', [
'@value' => $label,
]),
'#description' => $this
->t('Select the fields you want to display.'),
'#options' => $options,
];
if ($this->options['exposed_select_type'] == 'multi_select') {
$form[$field_id]['#type'] = 'select';
$form[$field_id]['#multiple'] = TRUE;
}
$form['fields_on_off_hidden_submitted'] = [
'#type' => 'hidden',
'#default_value' => 1,
];
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['fields'] = [
'default' => [],
];
$options['exposed_select_type'] = [
'default' => 'checkboxes',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$all_fields = $this->displayHandler
->getFieldLabels();
foreach ($all_fields as $key => $field) {
$exclude = $this->view->display_handler->handlers['field'][$key]->options['exclude'];
if ($exclude) {
unset($all_fields[$key]);
}
}
$field_options = array_slice($all_fields, 0, array_search($this->options['id'], array_keys($all_fields)));
$form['fields'] = [
'#type' => 'checkboxes',
'#title' => $this
->t('Fields'),
'#description' => $this
->t('Fields to be turned on and off.'),
'#options' => $field_options,
'#default_value' => $this->options['fields'],
];
$form['exposed_select_type'] = [
'#type' => 'radios',
'#title' => $this
->t('Exposed Selection Field Type'),
'#description' => t('Fields to be turned on and off.'),
'#options' => [
'checkboxes' => $this
->t('Checkboxes'),
'radios' => $this
->t('Radios'),
'select' => $this
->t('Single select'),
'multi_select' => $this
->t('Multiple select'),
],
'#default_value' => $this->options['exposed_select_type'],
];
}
public function query() {
}
}