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

1

8
#!/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")?

Rinaldo answered 12/8, 2011 at 15:41 Comment(4)
Did you try looking at the Documentation (search.cpan.org/~sri/Mojolicious-1.76/lib/Mojolicious/…)?Recognizor
search.cpan.org/~sri/Mojolicious-1.76/lib/Mojolicious/…Frankel
And those versions go away so fast... metacpan.org/module/Mojolicious::Lite#SessionsRespectful
Possible duplicate of Passing arguments to redirect_to in mojolicious and using them in the target controllerSartorial
E
8

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.

Emmott answered 26/8, 2011 at 12:47 Comment(3)
Which of these two methods would you prefer?Rinaldo
It absolutely depends on what you need and how you build your app. If you are passing parameters to the same application - flash is a good choice. However, passing query params is more failsafe: flash() method uses cookies to pass parameters around and also cookies are limiting you in params size more than query string. Personally I use both, but prefer query params in redirect. For example in auth process flash is really good: github.com/zipkid/mojolicious-login/blob/master/lib/Login/…Emmott
# + pass multiple url params as hash ref : my $url = $self->url_for('route_name') ; $c->redirect_to($url->query({'param_name1' => "$param_value1" , 'param_name2' => $param_value2}));Titanesque

© 2022 - 2024 — McMap. All rights reserved.