[dancer-users] list order from a hash

Andrew Beverley andy at andybev.com
Wed Aug 26 19:04:54 BST 2015


On Wed, 2015-08-26 at 12:39 -0500, Richard Reina wrote:
> > > I have this table data that I load into a template as follows.
> > > 
> > >   $q = "SELECT ID, NAME
> > >                 FROM jobs
> > >                 ORDER BY NAME";
> > >        $sth = $dbh->prepare($q);
> > >        $sth->execute();
> > >        my $Jobs_ref = $sth->fetchall_hashref('ID');
> > 
> > use fetchall_arrayref() instead.
> > 
> > > To display it in the template as a drop-down select I do:
> > > 
> > >     <select class="selectpicker" name="jobselect" id="jobselect"
> > > style="width: 500px;">
> > >               <% FOREACH ID IN Jobs.keys %>
> > 
> > Here you just need something like
> > 
> >     FOREACH job in Jobs
> > 
> > >         <option value="<% Jobs.$ID.ID %>"><% Jobs.$ID.NAME %></option>
> > 
> > And then here use job.ID, job.NAME etc.
>
> Thank you for the replies.  I am guessing that keeping the sorting in the
> SQL instead of the HTML would mean the page would load faster so I trying
> to go that route.
> 
> However, when I switch my code above to:
> 
>     <% FOREACH job in Jobs %>
>         <option value="<% job.ID %>"><% Job.NAME %></option>
>         <% END %>
> 
> I get an empty dropdown. I am using $sth->fetchall_arrayref(); with no
> arguments.

You might need to do:

    $sth->fetchall_arrayref({})

Sorry, it's been a while since I've done direct DBI calls. I'd recommend checking
out DBIx::Class if you have the time.

If you're still not having any luck, dump the result to see what you've got:

    use Data::Dumper;
    say STDERR Dumper $Jobs_ref;

Be careful of case-sensitivity, that could cause you problems too.

Andy





More information about the dancer-users mailing list