View separate exposed form sort elements

Exposed Form Elements

Sometimes, we have to separate exposed form elements in different templates.

But, If you want to render some elements without the exposed form it will not work at all.

And there is a solution to allow work expose form elements separated.

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MODULENAME_form_views_exposed_form_alter(array &$form, FormStateInterface $form_state): void {
  /** @var \Drupal\views\ViewExecutable $view */
  $view = $form_state->get('view');
  // Apply this code only for particular view.
  if ($view->current_display === 'VIEW_DISPLAY' && $view->id() === 'VIEW_ID') {
    $exposed_input = $view->getExposedInput();
    // We have to replace default sorting form element by the hidden field.
    // Without this hidden field the sorting functionality won't work.
    $form['sort_by'] = [
      '#type' => 'hidden',
      '#name' => 'sort_by',
      '#value' => $exposed_input['sort_by'] ?? array_key_first($view->display_handler->getOption('sorts')),
    ];
  }
}