Forums › Forums › Search & Filter Pro › Set selected item on filter
- This topic has 9 replies, 3 voices, and was last updated 7 years, 11 months ago by Anonymous.
-
Anonymous(Private) November 21, 2016 at 6:36 am #71326
I’m trying to set dropdown options programmatically.
But all of options on dropdown come out with “selected” attribute.
How do I set selected attribute properly to single option currently selected?function sf_input_object_pre_mod($input_object,$sfid){ if($sfid==123){ if($input_object['name']=='_sfm_event_month'){ $mons[] = date('Y-m', strtotime(date('Y-m-01'))); for($i=1;$i<=11;$i++){ $mons[] = date('Y-m', strtotime(date('Y-m-01').' +'.$i.' month')); } foreach($mons as $k=>$m){ $opt = new StdClass(); $opt->label = $m; $opt->attributes = array('class'=>'sf-level-0'); $opt->values = $m; $opt->count = 0; $input_object['options'][] = $opt; } } } return $input_object; } add_filter('sf_input_object_pre','sf_input_object_pre_mod',10,2);
Ross Moderator(Private) November 24, 2016 at 4:27 am #72015You should be able to add selected to an option by doing:
$opt->attributes = array('class'=>'sf-level-0', 'selected' => 'selected');
However this should be done automatically, as long as the value in the URL (ie what the user has selected matched the val found in one of your options)
Alternatively you might try to change the starting value (which would also change which is selected by following from here:
https://gist.github.com/rmorse/7b59b45a14b1ca179868
This would be the bit of code you would need to change initial value:
$input_object['defaults'] = array("black");
Even if its a single value, always put in an array..
** Edit **
Scratch all that.. I think I see the reason you might have an error. On your option you are setting
$opt->values = $m;
but an option only hasvalue
, like ->$opt->value = $m;
Thanks
Ross Moderator(Private) December 3, 2016 at 1:06 pm #73812Hey Ash
The best way to get the current value is to use our active query class:
https://www.designsandcode.com/documentation/search-filter-pro/accessing-search-data/
Because you want the actual value it might be best to use the array method and pull your value from there.
Alternatively, when using the sf_input_object_pre filter, the defaults should already be set to the current value from the URL, as its this default argument that is set by S&F and will be used to set the selected state.
Doing a var_dump of
$input_object['defaults']
should show the currently active value, if you access it at the top of your function before you’ve made any modifications (note: this will always be an array even for single selection type fields)Hope that makes sense?
-
AuthorPosts