1

I need to check a checkbox on an exposed filter for a view based on the url. I can't seem to figure out how to do that. If x is detected in the url, I want to set one of the fields of an exposed filter to have the status checked="checked." It seems like that would be pretty easy, but I can't seem to figure it out.

I have tried various ways through:

  • hook_views_pre_view()
  • hook_views_pre_build()
  • hook_form_views_exposed_form_alter() (I feel like this should be the best way.)

I've found that I can effectively alter the results through hook_views_pre_view(), but I can't figure out how to check that freaking checkbox on the exposed filter.

Varioush failed attempts via hook_form_alter():

  • $form["field_intended_use_target_id"]["#default_value"] = ['357'];
  • $form_state->input["field_intended_use_target_id"][356] = '356';
  • $form['field_intended_use_target_id']['widget'][0]['value']['#default_value'] = ['357'];

Can anyone please help?

7
  • try ['#default_value'] = 357; since value is not an array.
    – No Sssweat
    Nov 10, 2019 at 1:42
  • btw don't add single '' nor "" double quotes around numbers, because when you do that, you're making them "strings" type rather than "numeric".
    – No Sssweat
    Nov 10, 2019 at 1:46
  • No luck. Using xdebug I can see that it does in fact set the default value. But it still doesn't render with the checkbox checked. I checked source to confirm. I turned off my theme and used Bartik. Still no dice.
    – xpersonas
    Nov 10, 2019 at 1:49
  • Also tried removing quotes. Just can't seem to get that checked attribute for anything.
    – xpersonas
    Nov 10, 2019 at 1:51
  • I suggest you add a default value on your view's exposed filter settings, then check how the structure looks like, find where exactly the ['#default_value'] gets added inside $form array. Then you'll know where you need to put it.
    – No Sssweat
    Nov 10, 2019 at 1:51

2 Answers 2

1

I was finally able to achieve what I need via the hook_views_pre_build() hook.

Please let me know if this is wrong or if there is a better way, but from what I can tell this is the best way to achieve this.

function module_views_pre_build(ViewExecutable $view) {
  $termId = 357;
  $view->setExposedInput(['field_name' => [$termId => $termId]]);
}
0

You can use hook_form_alter() by adding view id condition. The use the code below, replacing FILTER_NAME with the name of your filter and set the necessary options.

$request = \Drupal::request();
if (!$request->get(FILTER_NAME, NULL)) {
  $input = &$form_state->getUserInput();
  $input[FILTER_NAME] = [
    'opt1' => 'opt1',
    'opt2' => 'opt2',
  ];
}

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.