Skip to content

Instantly share code, notes, and snippets.

@BD3i
Created January 11, 2024 12:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BD3i/48e290824066445b765d31e4790ee788 to your computer and use it in GitHub Desktop.
Save BD3i/48e290824066445b765d31e4790ee788 to your computer and use it in GitHub Desktop.
mojolicious select_field with selected option
<%
# this version works with index based numeric value keys
# note if you're storing this numeric value somewhere,
# you can never re-order the values and can only add to the end of the list
my $home_shows = 2; # current value
my $i = 0;
my @options = map { $i == $home_shows ? [$_ => $i++, selected => undef] : [$_ => $i++] }
qw(latest popular profile);
%>
<label class="label" for="home-shows">home shows</label>
%= select_field 'home-shows', \@options, id => 'home-shows'
<%
# this is a generic example where each option's value and label are the same string
# here you would be storing the string answer, not a number
my $home_shows = 'profile'; # current value
my @options = map { $_ eq $home_shows ? [$_ => $_, selected => undef] : [$_ => $_] }
qw(latest popular profile);
%>
<label class="label" for="home-shows">home shows</label>
%= select_field 'home-shows', \@options, id => 'home-shows'
<%
# this is an even more generic example, where the option's values and labels don't match
my $home_shows = 'Pro'; # current value
my @options = ([latest => 'Lat'], [popular => 'Pop'], [profile => 'Pro']); # [label => value]
@options = map { $_->[1] eq $home_shows ? [@$_, selected => undef] : $_ } @options;
%>
<label class="label" for="home-shows">home shows</label>
%= select_field 'home-shows', \@options, id => 'home-shows'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment