lift net.liftweb.http.S#param doesnt works like wiki says - scala

i try to copying the examples in wiki
http://wiki.liftweb.net/index.php/Hello_Darwin
in the example of HelloForm2.scala
"submit" -> submit(?("Send"), () => {println("value:" + who + " :: " + param("whoField"))}),
It always prints
value:Full(hogehoge) :: Empty" even if i set the who as "object who extends RequestVar(Full("world"))
am i do something wrong?
sorry for forgetting to post full code, i already try the second one in the wiki like below.
index.html
<lift:surround with="default" at="content">
<h2>Welcome to your project!</h2>
<lift:HelloWorld.show form="POST">
Hello <hello:who />
<br />
<label for="whoField">Who :</label>
<hello:whoField />
<hello:submit />
</lift:HelloWorld.show>
</lift:surround>
and HelloWorld.scala
class HelloWorld {
object who extends RequestVar(Full("world"));
def show(xhtml: NodeSeq): NodeSeq ={
bind("hello", xhtml,
"whoField" -> text(who.openOr(""), v => who(Full(v))) % ("size" -> "10") % ("id" -> "whoField"),
"submit" -> submit(?("Send"), () => {println("value:" + who.openOr("") + " :: " + param("whoField"))}),
"who" -> who.openOr("")
)
}
}
now, the who shows correct in the rendered page, but console still prints
value:hogehoge :: Empty
im using lift 1.0
thanks.

You have to change that code too, as shown in the example in the wiki page, which I'll copy here:
bind("hello", xhtml,
"whoField" -> text(who.openOr(""), v => who(Full(v))) % ("size" -> "10") % ("id" -> "whoField"),
"submit" -> submit(?("Send"), () => {println("value:" + who.openOr("") + " :: " + param("whoField"))}),
"who" -> who.openOr("")
)
Note that whoField is defined very differently.

Related

How to use hamlet template with route parameter?

I'm working on a yesod app based on the yesod-postgres stack template. I have a route defined in config/routes that has the form:
foo/edit/#Text EditFooR GET
In my hamlet template, I want to write
<form method=post action=#{EditFooR}#forms enctype=#{formEnctype}>
^{formWidget}
<button type="submit">
Submit
and in my Handler I'd like to write:
getEditFooR :: T.Text -> Handler Html
getEditFooR name = do
....
text <- findTextByName name
(formWidget, formEnctype) <- generateFormPost (editFooForm text)
defaultLayout $ do
$(widgetFile "editFoo")
Except that I need to provide the parameter to the #{EditFooR} route. How is this done in the Hamlet file/Handler?
The answer is that the .hamlet template should have the format:
<form method=post action=#{EditFooR fooName}#forms enctype=#{formEnctype}>
^{formWidget}
<button type="submit">
Submit
and the Handler should have the format:
getEditFooR :: T.Text -> Handler Html
getEditFooR name = do
....
text <- findTextByName name
fooName <- "something or other"
(formWidget, formEnctype) <- generateFormPost (editFooForm text)
defaultLayout $ do
$(widgetFile "editFoo")

How to solve in ReasonReact - "This has type: (ReasonReact.reactElement, string) => unit But somewhere wanted: at <anonymous>actElement

I have a very compact ReasonReact reducer component, which has a component, initialState, reducer, action, and render function as follows:
type actions =
| DoNothing;
let component = ReasonReact.reducerComponent("ShowHide");
let make = (~name, _children) => {
...component,
initialState: () => 0, /* here, state is an `int` */
reducer: (action, state) =>
switch action {
| DoNothing => ReasonReact.NoUpdate;
},
render: (self) => {
let greeting =
"Hello: " ++ name ++ ". You've clicked the button " ++ string_of_int(self.state) ++ " time(s)!";
<div></div>
}
};
I am trying to render in my app.re file using the ReactDOMRe.renderToElementWithId function:
<div id = "RenderShowHide"></div>
ReactDOMRe.renderToElementWithId(<ShowHide name="hello" />, "RenderShowHide")
However, the Reason/Bucklescript compiler is complaining as follows:
This has type:
(ReasonReact.reactElement, string) => unit
But somewhere wanted:
at <anonymous>actElement
However, I am having a difficulty what an actElement is. Any suggestions as to what an actElement is, and how I can go around fixing the above, would be more than appreciated. Thank you.
I tried the repo you posted: https://github.com/CharlieGreenman/reason-react-razroo
npm install
bsb -make-world
I got the following error message:
We've found a bug for you!
/Users/yawar/src/reason-react-razroo/src/app.re 16:9-40
14 ┆ </div>
15 ┆ <p className="App-intro">
16 ┆ ReactDOMRe.renderToElementWithId(<ShowHide name="hello"/>, "index")
17 ┆ (ReasonReact.stringToElement("To get started, edit"))
18 ┆ <code> (ReasonReact.stringToElement(" src/app.re ")) </code>
This has type:
(ReasonReact.reactElement, string) => unit
But somewhere wanted:
ReasonReact.reactElement
It looks like something in your build tooling was swallowing part of your error message. The main problem is on l. 16; if you get rid of that line the error will go away. If you want to render the ShowHide component, then change the line to just the literal JSX, not the call to ReactDOMRe.renderToElementWithId.
I have two more general recommendations; try to stick with the bsb-provided React skeleton project unless you are expert-level, because it's way simpler and much better supported:
bsb -init my-project -theme react
And, try to post the entire error message for future errors, starting from the 'We've found a bug for you!' line. That will help diagnose a lot.

Intelllij doesn't support Play Framework very well?

I am using Intellij Idea + Scala Plugin + Play framework 2.6.0 to do web development.
I have a FruitController, its definition is:
def saveFruit = Action(BodyParsers.parse.json) { request =>
import FruitImplicits._
val fruitResult = request.body.validate[Fruit]
fruitResult.fold(
errors => {
BadRequest(Json.obj("status" -> "KO", "message" -> JsError.toJson(errors)))
},
fruit => {
println(s"Fruit is saved, the result is :$fruit")
Ok(Json.obj("status" -> "OK", "message" -> ("Fruit '" + fruit.name + "' saved.")))
}
)
}
The Intellij idea complains Missing parameter type:request for the request in the first line: Action(BodyParsers.parse.json) { request =>
But I could run the code successfully, so Intellij Idea has been mistakenly reported the error, I would ask how to get Intellij Idea to work well for this code
When I explicitly specify the type of the request: Request[JsValue], the problem is gone:
def saveFruit = Action(parse.json) { request: Request[JsValue] =>

Scala xml : dependency between attributes

Our application receives an XML message from another system. The XML is structured like this:
<params>
<param name="FOO" value="BAR"/>
...
</params>
What is the best way, using Scala's native XML processing, to return the value BAR for the parameter which is FOO, so that:
val foo = "BAR"
Thanks
I assume your xml is invalid with missing param closing tag, it should be, for example
var x = <params>
<param name="FOO" value="BAR" />
<param name="FOO2" value="BAR2" />
</params>
If you want to extract the only param FOO, I don't think you will find anything much better than
(x \ "param" find (n => (n \ "#name").toString == "FOO")).get \ "#value"
If you want to get all params, you can iterate over them:
x \ "param" foreach {n => println(n \ "#name" + " -> " + n \ "#value")}

Play Scala activator compile command shows value userid is not a member of play.api.data.Form[models.Changepas sword]

I am new to play framework(Scala),In my project I need to update new Password for this I need to get user id which is Primary key for that user table. Based on this unique user id value i will update Password.
What I need
need to get user table's user id value and pass this value into Controller's Action
What I tried
controllers/users.scala
import play.api.mvc._
import play.api.data._
import play.api.data.Forms._
import views._
import models._
val changepasswordForm = Form(
mapping(
"userid" -> ignored(None:Option[Int]),
"password" -> tuple(
"main" -> text,
"confirm" -> text
).verifying(
// Add an additional constraint: both passwords must match
"Passwords don't match", passwords => passwords._1 == passwords._2
)
)(models.Changepassword.apply)(models.Changepassword.unapply)
)
def changePassword = Action {
Ok(html.changePassword(changepasswordForm))
}
def updatePassword(userid: Int) = Action { implicit request =>
changepasswordForm.bindFromRequest.fold(
formWithErrors => BadRequest(html.changePassword(formWithErrors)),
user => {
Changepassword.update(userid, user)
Ok("password Updated")
}
)
}
models/User.scala
case class Changepassword(
userid: Option[Int] = None,
password:(String,String)
)
object Changepassword{
val simple = {
get[Option[Int]]("user.USER_ID") ~
get[String]("user.PASSWORD") map {
case userid~password => Changepassword(userid, (password,password))
}
}
def update(userid: Int,changepassword:Changepassword) = {
DB.withConnection { implicit connection =>
SQL("update user set PASSWORD = {changepassword} where USER_ID = {userid}").
on('userid -> userid,
'changepassword -> changepassword.password._1)
.executeUpdate()
}
}
}
views/changePassword.scala.html
#(userForm: Form[Changepassword])
#import helper._
#implicitFieldConstructor = #{ FieldConstructor(twitterBootstrapInput.f) }
#main("") {
<h1>Change Password</h1>
#form(routes.Users.updatePassword(userForm.userid.get)) {
<fieldset>
#inputPassword(userForm("password.main"), '_label -> "New Password", '_help -> "",'placeholder -> "New Password")
#inputPassword(userForm("password.confirm"), '_label -> "Confirm Password", '_help -> "",'placeholder -> "Repeat Password")
</fieldset>
<div class="actions">
<input type="submit" value="Change password" class="btn primary"> or
Cancel
</div>
}
}
If I run activator compile command it shows below exception
D:\Jamal\test>activator compile
[info] Loading project definition from D:\Jamal\test\p
roject
[info] Set current project to scala-crud (in build file:/D:\Jamal\test/)
[info] Compiling 1 Scala source to D:\Jamal\test\targe
t\scala-2.11\classes...
[error] D:\Jamal\test\app\views\changePassword.sc
ala.html:11: value userid is not a member of play.api.data.Form[models.Changepas
sword]
[error] #form(routes.Users.updatePassword(userForm.userid.get)) {
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 13 s, completed Jun 11, 2015 3:52:19 PM
D:\Jamal\test>
You can't use the value of the form as a parameter for the route:
#form(routes.Users.updatePassword(userForm.userid.get))
The userid depends on the form and could therefore change. In any case, you would access the userid of the form using userForm("userid") and not userForm.userid (although it might not be what you want/need).
A better approach for your problem would be to pass a second parameter like this:
controllers/users.scala
def changePassword = Action {
val userId = ... get the current id ...
Ok(html.changePassword(changepasswordForm,userId))
}
views/changePassword.scala.html
#(userForm: Form[Changepassword], userId:Int)
...
...
#form(routes.Users.updatePassword(userId)) {
...
...
}
...
This way, you ensure the userId is known when the page is displayed and that a "evil" user can't change the passwords of other users by manipulating the userId.