Is there a way to sort view asc or desc using

drupal_view('vn', 'vmn', sort order) 

in twig

or Can sort we views_embed_view() in controller

  • 3
    Why do you need to do it? What's wrong with setting in the Views UI and then print it like you already do? – leymannx Jan 19 at 11:12
  • @leymannx I am using expose filter where I have option like olderst first and new first While click on Newset first I am taking date as Now and its working. Now i want oldest first in that I am using custom ajax call to render view. Is possible using CONTETUAL filter or any other solution – top Jan 19 at 12:40
  • 1
    Looking at the Cheat sheet for drupal_view(), it doesn't look like there's an option for sort order. – sonfd Jan 19 at 13:09
  • Thanks @sonfd Can I achieve it with contextual filter or do you have any other solution. Like hook_view_alter_alter to achieve this. – top Jan 19 at 13:21
  • 2
    Have you considered using the "Allow users to choose the sort order" option that views provides. Rather than trying to build your own special method to do it with an exposed filter? – sonfd Jan 19 at 13:27

One alternative approach is to use the exposed sort options provided by Views. Adding exposed sort options is similar to adding exposed filters:

  1. Add a sort option in the Sort Criteria section of the View UI. (It's right below the Filter Criteria section)
  2. For the sort options you want exposed, check the box to "Expose this sort to visitors, to allow them to change it"

This will expose a select widget to the end user allowing them to choose which of the sort criteria should be used to sort the View. For example, if you choose to expose a Title sort and a Date sort, the end user would see a select field allowing them to choose which sort by Title or sort by Date.

Additionally, you can also expose the sort order for your exposed sort items. For example, choose whether it's Title ASC or Title DESC. To do this, open the Exposed Form > Settings options, in the Advanced tab, and check the box for "Allow people to choose the sort order".

I'd recommend using these options to interface with the backend view and query. If the UX isn't to your liking, perhaps you could render your own select field on the frontend and then set these default views fields per the value selected in your select field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.