Jump to content

Recommended Posts

Posted

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>

 

Posted

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
  • 2 years later...
Posted

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>

 

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
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...