diff --git a/src/Plugin/views/field/ViewsCsvField.php b/src/Plugin/views/field/ViewsCsvField.php index b031542586a38f40d28e856ad3a438bfac99450c..f53738105852bf485b2d53f8fbc014b966e8e37e 100644 --- a/src/Plugin/views/field/ViewsCsvField.php +++ b/src/Plugin/views/field/ViewsCsvField.php @@ -7,6 +7,8 @@ use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Render\Markup; use Drupal\views\Plugin\views\field\FieldPluginBase; use Drupal\views\ResultRow; +use Drupal\views_csv_source\Plugin\views\query\ViewsCsvQuery; +use League\Csv\Reader; /** * Base field handler for views_csv_source. @@ -66,13 +68,42 @@ class ViewsCsvField extends FieldPluginBase { */ public function buildOptionsForm(&$form, FormStateInterface $form_state) { parent::buildOptionsForm($form, $form_state); - $form['key'] = [ - '#title' => $this->t('Column Selector'), - '#description' => $this->t('Choose a column'), - '#type' => 'textfield', - '#default_value' => $this->options['key'], - '#required' => TRUE, - ]; + + // Get the connection service. + $connection = \Drupal::service('views_csv_source.connection'); + // Get the query. + $query = $this->view->query; + // Ensure the query is of the correct type. + if ($query instanceof ViewsCsvQuery) { + // Access the options array from the query object. + $csv_uri = $query->options['csv_file']; + $csv = Reader::createFromString($connection->fetchContent($csv_uri)); + // Get headers from the CSV file. + $headers = $csv->nth(0) ?? []; + $options = []; + foreach ($headers as $header) { + $options[$header] = $header; + } + $form['key'] = [ + '#title' => $this->t('Column Selector'), + '#description' => $this->t('Choose a column'), + '#type' => 'select', + '#options' => $options, + '#default_value' => $this->options['key'], + '#required' => TRUE, + ]; + } + else { + // Fall back to text value if CSV has not been selected. + $form['key'] = [ + '#title' => $this->t('Column Selector'), + '#description' => $this->t('Choose a column'), + '#type' => 'textfield', + '#default_value' => $this->options['key'], + '#required' => TRUE, + ]; + } + $form['trusted_html'] = [ '#title' => $this->t('Trusted HTML'), '#description' => $this->t('This field is from a trusted source and contains raw HTML markup to render here. Use with caution.'),