How to change Drupal 8 Datelist select array order - Tutorial

in tech •  7 years ago 

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.


drupal_logo.png

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

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

good content

good...
i followed u pls follow me too

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


Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Congratulations @gprtskh! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 2 years!

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:

The Steem community has lost an epic member! Farewell @woflhart!
SteemitBoard - Witness Update
Do not miss the coming Rocky Mountain Steem Meetup and get a new community badge!
Vote for @Steemitboard as a witness to get one more award and increased upvotes!