A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.playframework.com/documentation/2.5.x/api/scala/play/api/mvc/QueryStringBindable.html below:

QueryStringBindable - play.api.mvc.QueryStringBindable

Binder for query string parameters.

You can provide an implementation of QueryStringBindable[A] for any type A you want to be able to bind directly from the request query string.

For example, if you have the following type to encode pagination:

/**
 * @param index Current page index
 * @param size Number of items in a page
 */
case class Pager(index: Int, size: Int)

Play will create a Pager(5, 42) value from a query string looking like /foo?p.index=5&p.size=42 if you define an instance of QueryStringBindable[Pager] available in the implicit scope.

For example:

object Pager {
  implicit def queryStringBinder(implicit intBinder: QueryStringBindable[Int]) = new QueryStringBindable[Pager] {
    override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Pager]] = {
      for {
        index <- intBinder.bind(key + ".index", params)
        size <- intBinder.bind(key + ".size", params)
      } yield {
        (index, size) match {
          case (Right(index), Right(size)) => Right(Pager(index, size))
          case _ => Left("Unable to bind a Pager")
        }
      }
    }
    override def unbind(key: String, pager: Pager): String = {
      intBinder.unbind(key + ".index", pager.index) + "&" + intBinder.unbind(key + ".size", pager.size)
    }
  }
}

To use it in a route, just write a type annotation aside the parameter you want to bind:

GET  /foo        controllers.foo(p: Pager)

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4