louisstephens Posted July 17, 2018 Share Posted July 17, 2018 I have a Select options field in a template, and I was wondering if it is possible to get all the options from the field (in context to the page) and output them with the current selected option selected? So the output would be something like: <select class="statuses"> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> <option value="four" slected>Four</option> </select> Link to comment Share on other sites More sharing options...
elabx Posted July 17, 2018 Share Posted July 17, 2018 Use this to get all the options, iterate on it and just check if the value equals the page field value: $field = $fields->get('countries'); $all_options = $field->type->getOptions($field); Check the documentation for more useful on select options fields: https://processwire.com/api/modules/select-options-fieldtype/#outputting-selected-options-on-a-page Link to comment Share on other sites More sharing options...
louisstephens Posted July 17, 2018 Author Share Posted July 17, 2018 Thanks elabx, I cant believe I missed that. I found people discussing $page->optionsfield->has("value=foo") to check if a value was selected, but since this options field might have a bunch of options, it seems a bit much to have to define each foreach. I tried: <?php if($option->has("title={$option->title}")): ?> but I have apparently missed how to do this. Yeah, I really just was not thinking, I got it with: <?php $field = $fields->get('my_field'); $options = $field->type->getOptions($field); $selectedField = $todo->my_field->value; ?> <select> <?php foreach($options as $option): ?> <?php if($option->value === $selectedField): ?> <option value="<?=$option->value;?>" selected><?=$option->title;?></option> <?php else: ?> <option data-id="<?=$page->parent->id;?>" value="<?=$option->value;?>"><?=$option->title;?></option> <?php endif; ?> <?php endforeach; ?> </select> 1 Link to comment Share on other sites More sharing options...
pwfans Posted June 30, 2021 Share Posted June 30, 2021 Or using ternary operator : <select> <?php $field = $fields->get('field_name'); $options = $field->type->getOptions($field); $selectedField = $page->field_name->title; foreach ($options as $option) { echo "<option value='".$option."' ".($option->title == $selectedField ? "selected":"").">".$option->title.'</option>'; } ?> </select> Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now