In this tutorial I am going to teach you how to change Datelist select array order in Drupal 8.
First of all we have Datelist type form element in our form.
$form['FIELD_NAME'] = [
'#type' => 'datelist',
'#title' => $this->t('FIELD TITLE'),
'#required' => TRUE,
'#date_part_order' => ['day', 'month', 'year'],
'#date_year_range' => '1917:2020',
];
Default select list options are sorted ascending order, from 1917 to 2017, but in some cases we want to reverse it.
To reverse ordering we need to add function THEME_NAME_preprocess_select in our custom theme THEME_NAME.theme file.
function THEME_NAME_preprocess_select(&$variables) {
if ($variables['element']['#name'] == 'FIELD_NAME[year]') {
$select_options = $variables['options'];
$select_label_option = $select_options[0];
unset($select_options[0]);
$reversed_select_options = array_merge(
[$select_label_option], array_reverse($select_options)
);
$variables['options'] = $reversed_select_options;
}
}
And finally we get year select with reversed options from 2017 to 1917.
Hope you enjoyed reading this tutorial. I am going to write more and more tutorials for learning Drupal, so please don't forget to upvote, comment and follow