Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mojolicious::Lite: How to pass parameters when using "redirect_to";

#!/usr/local/bin/perl
use warnings;
use 5.014;
use Mojolicious::Lite;
use DBI;

# ...

get '/choose' => sub {
    my $self = shift;
    my $lastname = $self->param( 'lastname' );
    my $sth = $dbh->prepare( "SELECT id, firstname, birthday FROM $table WHERE lastname == ?" );
    $sth->execute( $lastname );
    my @rows;
    while ( my $row = $sth->fetchrow_hashref ) {
        push @rows, { id => $row->{id}, firstname => $row->{firstname}, lastname => $lastname, birthday => $row->{birthday} };
    }
    if ( not @rows ) {
        $self->redirect_to( 'new_entry' );
    } elsif ( @rows == 1 ) {
        my $id = $rows[0]{id};
        $self->redirect_to( "/show_address?id=$id" );   # show_address needs parameter "id"
    } else {
        $self->stash( rows => \@rows );
        $self->render( 'choose' );
    }
};

# ...

When I use redirect_to, is there another way to pass a parameter than writing it directly in the url ("/show_address?id=$id")?

like image 397
sid_com Avatar asked Aug 12 '11 15:08

sid_com


1 Answers

redirect_to can build url for you and replace placeholders in your routes with your params.

If you need to build url with params you can do following:

my $url = $self->url_for("/show_address");
$self->redirect_to($url->query(id => $id));

Also note that you can pass parameters with query by setting flash variables: http://mojolicio.us/perldoc/Mojolicious/Controller#flash

That variables will be cleaned up by Mojolicious with next request.

like image 111
yko Avatar answered Oct 19 '22 23:10

yko