1

I have a view which show products and an exposed filter block (category, manufacturer, price).

I want to set category default value from URL, like this:

/browse-products/category-id

though, I wrote this module which take the parameter from URL and put it into exposed filter default value.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $request;

  if ($form_id == 'views_exposed_form') {
    $category_id = (int)($request->attributes->get('_raw_variables')->get('arg_0'));
    $form['category_id']['#default_value'][$category_id] = $category_id;
    dpm($form['category_id']);
  }
}

dpm output for /browse-products/5

Array
    (
        [#type] => checkboxes
        [#multiple] => 1
        [#options] => Array
            (
                [5] => Tablets
                [10] => -Ainovo
                [7] => -Galaxy Tab
                [6] => -IPad
                [1] => Smart Phones
                [4] => -Galaxy
                [3] => -IPhone
                [9] => --IPhone C
                [8] => --IPhone X
            )

        [#size] => 9
        [#default_value] => Array
            (
                [5] => 5
            )

        [#bef_nested] => 1
        [#theme] => bef_checkboxes
    )

but it doesn't work?

another thing, why dpm($form) prints the views exposed form data twice!

update 1: I tried something like this (but didn't work):

function mymodule_views_pre_build(Drupal\views\ViewExecutable $view) {
    $view_filters = $view->display_handler->getOption('filters');
    $view_filters['field_category_target_id']['value'][8] = 8;
    $view->display_handler->setOption('filters', $view_filters);
}

or this:

function mymodule_views_pre_build(Drupal\views\ViewExecutable $view) {
  $filters = $view->getExposedInput();
  $filters['field_category_target_id'] = 8;
  $view->setExposedInput($filters);
}

1 Answer 1

0

The #default_value parameter should be set to the key of the select list array.

Example:

$form['category_id']['#default_value'] = $category_id;
2
  • it didn't work (in the exposed form, no category is checked), (and the view data aren't filtered). it looks like I have to set value some were else, not just in the exposed form!
    – Wisamx
    Commented Jul 5, 2018 at 10:55
  • I added some codes to the main post
    – Wisamx
    Commented Jul 5, 2018 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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