Jump to content

Possbile to list all options (and set current selected option)


louisstephens
 Share

Recommended Posts

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

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

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>

 

  • Like 1
Link to comment
Share on other sites

  • 2 years later...

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    No registered users viewing this page.

×
×
  • Create New...