I need to add sorting to a view in code but can't seem to get this to work. This is my code so far.

$view = Views::getView('name_of_the_view');
if (!$view) {
  // some irrelevant code to handle a non existing view


As far as I know, I need to add $view->sort and $view->filter before the execute method but don't know what to set this to.

Do I have to pass the name of the sort/filter handler (i.e. 'random') or the class name (i.e. Drupal\views\Plugin\views\sort\Random) or an instance of a sort/filter handler or something else?


I was confused by $view->setExposedInput saying it accepts $filters as argument, but it actually works for sorting as well. So with that function you can set your exposed filters AND sorts

  'your_filter' => $your_filter_value, //your exposed filter
  'sort_by' => 'your_field', //your exposed sort
  'sort_order' => 'ASC',

Use above code before you execute view.

And make sure you exposed your filters and sorts in your view.

  • I am actually using this at the moment and it does work. Too bad that the exposed filters have to be set in views rather than in code. – diesonne Jul 25 '16 at 11:31

Views::getView() returns a ViewsExecutable object for which the following public properties are defined:

So, to add a filter in the view you loaded, you should use $views->filter[] = $filter_object.

  • could you provide a simple example? – diesonne Jul 20 '16 at 6:54
  • any update on this ? It really looks like the way to go – diesonne Sep 7 '16 at 8:32
  • 1
    setting a value can be done with $view->setHandlerOption() and you pretty much can get all the needed values from the exported view yml file – hugronaphor Oct 10 '18 at 13:45

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.