Add sorting and filtering in code 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
}
$view-&gt;setDisplay('name_of_the_display');
$view-&gt;setArguments([$searchString]);
$view-&gt;setCurrentPage($page); 

$view-&gt;execute();


As far as I know, I need to add $view-&gt;sort and $view-&gt;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-&gt;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

$view-&gt;setExposedInput([
  'your_filter' =&gt; $your_filter_value, //your exposed filter
  'sort_by' =&gt; 'your_field', //your exposed sort
  'sort_order' =&gt; 'ASC',
]);


Use above code before you execute view.

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