I am trying to figure out how to do a redirect within a controller action in Play (2.0) using Scala.
The redirect using
Redirect(routes.Application.index)
works just fine.
What I cannot figure out from the docs, API, or Google is how to add parameters to the call.
I am coming from Grails where this could be done easily as follows:
redirect action: "index", params: ["key": "value"]
.
The only way I have found is to call Redirect using a string url and a query string, which seems awkward.
Basically I would like to make use of Redirect(Call) somehow, but I do not how to create the Call object using reverse routing.
Am I missing something/not getting the concept in Play/Scala?
Thanks in Advance!
Ellou'
A route is just a function, so you can pass arguments as usual:
// Redirect to /hello/Bob
def helloBob = Action {
Redirect(routes.Application.hello("Bob"))
}
This snippet comes from http://www.playframework.org/documentation/2.0/ScalaRouting (at the bottom)
You can also avoid creating another function just for this in your controller. In your route config, you can simply add something like this:
GET /google #controllers.Default.redirect(to = "http://google.com")
Related
I am new to Scala/Play Framework.
Currently, I am trying to call a Scala function from my html page: test.scala.html and pass the hash parameters to the Scala function.
I added the following lines to routes:
GET /hello controllers.Application.test
POST /hello controllers.Application.hello
In my test.scala.html I have:
#params = { window.location.hash }
#helper.form(action = routes.Application.hello) {
}
And my hello function is defined as:
def hello() = Action {
Ok("Hello !")
}
I am completely confused by the concept of routing and # so I am not too sure which part I did right and which part I did wrong. Please point out my mistakes.
Thanks in advance.
If the function is returning an action, not content to be displayed formatted inside view (HTML), you may want to route request to this action, from a link click or a form submit, to url configured in routing (aka /hello).
To add a parameter you need to either add it as url query string (e.g. for a link → /hello?p=1), or with an input/field for a form (e.g. <input type="text" name="p" value="1" />).
You can use reverse routing to get URL to call configured action. For example for a form POST to hello: <form action="#routes.MyController.hello()" method="POST">.... In this case you will need to look at form mapping, to extract parameters from request.
1) Concept of routing
The main purpose of this routing is simply to translate each incoming HTTP request to an Action in any of your Controller. By Reverse Routing its simply let you use the right part, controllers.Application.hello, in your HTML/Controller/else.
So, for your 2 URLs above, it's likely to say that if there is a request /hello with method GET then it will go to Application controller and test method. If you don't understand the role of each Routing method, please read this documentation..
2) the magic # character
# is a character that you can use in your HTML file if you need to use the Scala code or variables. It's like you can combine PHP code in your HTML file, if you're a PHP developer.
Here is the full-documentation of what you can do with this # character.
3) pass the hash to the controller
To this specific case the simplest way would be passing the value trough a form:
#helper.form(action = routes.Application.hello) {
#helper.inputText(myForm("username"), 'id -> "username", 'size -> 30, 'value -> 'value here' )
}
However, if you're a new Play developer, then I'm afraid you need to read about Form Submission and Form Helper in Play Framework..
Is it possible to create a REST endpoint in play like:
/users/new
That would also call a method named new ?
I tried doing this like:
def `new`:= {
...
}
The action worked fine, but the line in my route file was not working because of the new keyword:
GET /users/new #controllers.UserController.new
I like following the rubyonrails convention with URL endpoints.
I am not a expert but try this:
GET /users/new #controllers.UserController.new()
Also your function new() is under UserController class?
new is reserved word in Java at least. I made successfully controller:
GET /user/new controllers.UserController.news()
I want to call another internal url from my scalatra 'controller'. I can't do a simple redirect, as there's some security settings that mean a user has access only to the first url.
Is there a way to do this?
get("/foo") {
servletContext.getRequestDispatcher("/bar").forward(request, response)
}
The get() method is defined as (similar to POST, et al):
def get(transformers : org.scalatra.RouteTransformer*)(action : => scala.Any) : org.scalatra.Route
Depends on what you mean by internal redirect, I presume you just want to execute another route's action. You have a few options of what you can do. This seems to be working for me:
val canonicalEndpoint = get("/first/route") {
//do things in here
}
Then you could subsequently do:
get("/second/route")( canonicalEndpoint.action )
And I think you would get your desired response.
I like saving the whole Route response of the get() as you may also want to use that with scalatra's url() function in routing.
I have several routes defined in my application.
When route A is matched and I assemble an URL using route B without resetting, it does not include the current request parameters.
Is there an easy way to include all the request parameters when assembling an URL via a different route than the current route?
I did have a look at Zend_Controller_Router_Rewrite->useRequestParametersAsGlobal, but this will (obviously) also include the request parameters when reset = true
You could try the following.
$oldParams = $this->_getAllParamas();
unset($oldParams['module']);
unset($oldParams['controller']);
unset($oldParams['action']);
Pass
array_merge(array('new'=>'param'),$oldParams)
to your URL view helper.
I am developing a website using zend framework.
i have a search form with get method. when the user clicks submit button the query string appears in the url after ? mark. but i want it to be zend like url.
is it possible?
As well as the JS approach you can do a redirect back to the preferred URL you want. I.e. let the form submit via GET, then redirect to the ZF routing style.
This is, however, overkill unless you have a really good reason to want to create neat URLs for your search queries. Generally speaking a search form should send a GET query that can be bookmarked. And there's nothing wrong with ?param=val style parameters in a URL :-)
ZF URLs are a little odd in that they force URL parameters to be part of the main URL. I.e. domain.com/controller/action/param/val/param2/val rather than domain.com/controller/action?param=val¶m2=val
This isn't always what you want, but seems to be the way frameworks are going with URL parameters
There is no obvious solution. The form generated by zf will be a standard html one. When submitted from the browser using GET it will result in a request like
/action/specified/in/form?var1=val1&var2=var2
Only solution to get a "zendlike url" (one with / instead of ? or &), would be to hack the form submission using javascript. For example you can listen for onSubmit, abort the submission and instead redirect browser to a translated url. I personally don't believe this solution is worth the added complexity, but it should perform what you're looking for.
After raging against this for a day-and-a-half, and doing my best to figure out the right way to do this fairly simple this, I gave up and did the following. I still can't believe there's not a better way.
The use case that necessitates this is a simple record listing, with a form up top for adding some filters (via GET), maybe some column sorting, and Zend_Paginate thrown in for good measure. I ran into issues using the Url view helper in my pagination partial, but I suspect with even just sorting and a filter-form, Zend_View_Helper_Url would still fall down.
But I digress. My solution was to add a method to my base controller class that merges any raw query-string parameters with the existing zend-style slashy-params, and redirects (but only if necessary). The method can be called in any action that doesn't have to handle POSTs.
Hopefully someone will find this useful. Or even better, find a better way:
/**
* Translate standard URL parameters (?foo=bar&baz=bork) to zend-style
* param (foo/bar/baz/bork). Query-string style
* values override existing route-params.
*/
public function mergeQueryString(){
if ($this->getRequest()->isPost()){
throw new Exception("mergeQueryString only works on GET requests.");
}
$q = $this->getRequest()->getQuery();
$p = $this->getRequest()->getParams();
if (empty($q)) {
//there's nothing to do.
return;
}
$action = $p['action'];
$controller = $p['controller'];
$module = $p['module'];
unset($p['action'],$p['controller'],$p['module']);
$params = array_merge($p,$q);
$this->_helper->getHelper('Redirector')
->setCode(301)
->gotoSimple(
$action,
$controller,
$module,
$params);
}