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
good content
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
good...
i followed u pls follow me too
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @gprtskh! You have received a personal award!
1 Year on Steemit
Click on the badge to view your Board of Honor.
Do not miss the last post from @steemitboard!
Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @gprtskh! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit