Sorting with select menu

I think I need an other pair of eyes on this…
I’m trying to make a select menu with three sorting options using param() like this :

if($tag = urldecode(param('authors_notice_only_name'))) {
      $articles = $articles->sortBy('authors_notice_only_name', 'asc');
if($tag = urldecode(param('date_creation'))) {
      $articles = $articles->sortBy('date_creation', 'desc');
if($tag = urldecode(param('acquisition_year'))) {
      $articles = $articles->sortBy('acquisition_year', 'desc');

and my select menu looks like :

<option value="<?= url($page->url(), ['params' => ['classement' => 'acquisition']]) ?>">Par année d’acquisition</option>
<option value="<?= url($page->url(), ['params' => ['classement' => 'annee_creation']]) ?>">Par année de création</option>
<option value="<?= url($page->url(), ['params' => ['classement' => 'alpha']]) ?>">Par ordre alphabétique</option>

The url is well created, but my code doesn’t sort my articles, can we ? (with sorting method ?). My goal is to have an URL like “classement:…” in order to sort my $articles by date_creation, authors_notice_only_name and acquisition_year.

I don’t kwnow why, I’m often lost with tag, param() and the logic behind this…Do you have any clue ?

Your parameter name is classement not authors_notice_only_name etc., so the parameter name doesn’t change, only the value of that parameter.

Your code can be shortened to

if($tag = urldecode(param('classment'))) {
      $articles = $articles->sortBy($tag, 'asc');

Since your sorting order depends on the value of tag, you need an if statement to get the right sort order.

$tag = urldecode(param('classment');
if($tag)) {
      $sortOrder = $tag === 'authors_notice_only_name' ? 'asc' : 'desc';
      $articles  = $articles->sortBy($tag, $sortOrder);

Thank you very much, it works
I’ve written my code like this to make it works with my three parameters,

$tag = urldecode(param('classement'));
   if($tag) {
      $sortOrder = $tag === param('classement') ? 'asc' : 'desc';
      $articles  = $articles->sortBy($tag, $sortOrder);

But I would like to separate sorting method:

  • authors_notice_only_name → asc
  • date_creation → desc
  • acquisition_year → desc

Do I have to separate condition or is there an more elegant way to do it ?

This doesn’t make sense, this condition is always true when a parameter is set, you have to compare against a specific value, see above, maybe my value was wrong, then just change it.

Also make sure that the parameter values are the same as the fields you want to sort by, in your first post you had acquisition, ’ annee_creation’ and alpha as parameter values, but then your fields to sort by are date_creation, acquisition_year and authors_notice_only_name. That somehow doesn’t make sense.

So what I’m trying to say is that your parameter values must be identical to the field names you want to sort by.