Drupal 8, alter a view for display the n firsts results

I created a view via the view user interface. From a custom module, I want alter the view for display the n firsts results depending of some user parameters.

I don’t find how I can do that with views alter hook functions..

By example, via the pre execute view alter hook,

The “limit” value define the value in the current page with the limit of the of pager (10 results of the 27 results are displayed in pager 1, 10 results of the 27 results are displayed in pager 2 and 7 results of the 27 results are displayed in pager 3). The “limit” doesn’t define the total number of the result query.

I tried this :

    function mymodule_views_query_alter(ViewExecutable $view, DrupalviewsPluginviewsqueryQueryPluginBase $query){
    
        if($views->id() == "mycustomview"){
            $view->query->setLimit(7);
            $view->query->setOffset(5);
            $view->save();
            
            // I try also ..
            // $query->setLimit(7);
            // $query->setOffset(5);
        }
    }

But my view in the view page doesn’t change and display 10 results (number total of node).

I tried also this :

function mymodule_views_query_alter(DrupalviewsViewExecutable $view, DrupalviewsPluginviewsqueryQueryPluginBase $query){

if($views->id() == “mycustomview”){
$query->setLimit(3);
ksm(“Hey ! I pass here !”); // log function
}
}

in drupal/modules/custom/mymodule/mymodule.module file

OR

in in drupal/modules/custom/mymodule/mymodule.views_execute.inc file

and I clear caches with “drush cr”

=> My view page display my log (“Hey ! I pass here !”), BUT, my view always display ALL result :/

How can I configure this structure for not display all results by display only n first results ?

Drupal version: 


Source: https://www.drupal.org/taxonomy/term/4/feed