how to get autocomplete text box value using lift web - scala

I am using Lift web framework.
I am implementing an auto-complete text box. When I enter some value in the box a drop-down list opens. If I select a value from that list, only then I am able to access value of text box. If I write a value by myself then I get an empty value.
My code :
var friend_name=""
"#bdayReminder" #> AutoComplete("",
getAllName _,
value => takeAction(value),
List("minChars" -> "3"))
private def takeAction(str: String) {
friend_name = str
}
Please suggest a solution

Disclaimer: I'm the author of following library.
I think lift-combobox could achieve what you want, since it has a feature that let user created the value on-the fly. It use select2 jQuery plugin, so you will have a nice look and feel for the drop-down menu.
For example if you need to get the user-created value, it will simply as the following, note that we usually using Option[T] to denote that the value may not be presented, for example, the user may not selected any item in drop-menu at all:
var friend_name: Option[String] = None
val friendsMenu = new ComboBox(
default = None,
allowCreate = true
) {
// This is where you build your combox suggestion
override def onSearching(term: String): List[ComboItem] = {
val names = List(
ComboItem("f1", "Brian"), ComboItem("f2", "Alice"),
ComboItem("f3", "Luke"), ComboItem("f4", "Smith"),
ComboItem("f5", "Brandon")
)
names.filter(_.text.contains(term))
}
override def onItemSelected(selected: Option[ComboItem]): JsCmd = {
friend_name = selected
// The returned JsCmd will be executed on client side.
Alert("You selected:" + selected)
}
// What you want to do if user added an item that
// does not exist when allowCreate = true.
override def onItemAdded(text: String): JsCmd = {
friend_name = Some(text)
}
}
"#bdayReminder" #> friendsMenu.combobox

Related

How to reset a table

It's possible to reset a table scala swing or remove it from the container after clicking on a button ?
I've tried to create a val with that table but I have always a new table stacked under the old
Here is the code :
// here is the most crucial part when the user click on the button, it will append a new table but if we want to start again, it will append bottom of the old one and I want here a kind of reset or removing of table
contents = new BoxPanel(Orientation.Vertical) {
contents += new Label("Hello, you're welcome")
contents += Button("Query") {
val query: ScrollPane = new ScrollPane(changeCountry())
contents -= query
Try {
contents += query
}.getOrElse(Dialog.showMessage(contents.head, "Incorrect input ! This seems that input isn't in that list, write a different code or country"))
}
// this part will ask to the user to write text to the input to display the table in function of the parameter of my function
def changeCountry(): Table = {
val text = Dialog.showInput(parent = contents.head, message = "Write a code of a country or a country", initial = "test")
text match {
case Some(s) => airportRunwayByCountry(s)
}
}
// this below part creates the table
def airportRunwayByCountry(code : String): Table = {
val headers = Seq("Airport","Runway linked")
val rowData = Functions.findAirportAndRunwayByCountry(code).map(x => x.productIterator.toArray).toArray
val tableAirportRunway = new Table(rowData,headers)
tableAirportRunway}
}
Solved with method "remove" of containers
Here is the code :
Try {
if(contents.length == 3 \\ number of items in my Box) {
\\ at this moment, only add the table because none other table exists
contents += new ScrollPane(changeCountry())
}
else {
contents -= contents.remove(3) \\get the id of the old table and remove it at this position
contents += new ScrollPane(changeCountry()) \\ at this moment, this content will have the id n°2, and the loop can start over without errors
}

How do I update a MongoDB document with new value using reactors Mono? (Kotlin)

So the context is that I require to update a value in a single document, I have a Mono, the parameter Object contains values such as username (to find the correct user by unique username) and an amount value.
The problem is that this value (due to other components of my application) is the value by which I need to increase/decrease the users balance, as opposed to passing a new balance. I intend to do this using two Monos where one finds the user, then this is combined to the other Mono with the inbound request, where I can then perform a simple sum (i.e balance + changeRequest.amount) then return this to the document database.
override fun increaseBalance(changeRequest: Mono<ChangeBalanceRequestResource>): Mono<ChangeBalanceResponse> {
val changeAmount: Mono<Decimal128> = changeRequest.map { it.transactionAmount }
val user: Mono<User> = changeRequest.flatMap { rxUserRepository.findByUsername(it.username)
val newBalace = user.map {
val r = changeAmount.block()
it.balance = sumBalance(it.balance!!, r!!)
rxUserRepository.save(it)
}
.flatMap { it }
.map { it.balance!! }
return Mono.just(ChangeBalanceResponse("success", newBalace.block()!!))
}
Obviously I'm trying to achieve this in a non-blocking fashion. I'm also open to using only a single Mono if that's possible/optimal. I also appreciate I've truly butchered the example and used .block as a placeholder to illustrate what I'm trying to achieve.
P.S this is my first post, so any tips on how to express my problem clearer would be useful.
Here's how I would do this in Java (Using Double instead of Decimal128):
public Mono<ChangeBalanceResponse> increaseBalance(Mono<ChangeBalanceRequestResource> changeRequest) {
Mono<Double> changeAmount = changeRequest.map(a -> a.transactionAmount());
Mono<User> user = changeRequest.map(a -> a.username()).flatMap(RxUserRepository::findByUsername);
return Mono.zip(changeAmount,user).flatMap(t2 -> {
Double changeAmount = t2.getT1();
User user = t2.getT2();
//assumes User is chained
return rxUserRepository.save(user.balance(sumBalance(changeAmount,user.balance())));
}).map(res -> new ChangeBalanceResponse("success",res.newBalance()))
}

How do I handle data entry in a scala.js bootstrap modal dialog?

I am using scala.js, plus the bootstrap facade, to collect some data from my user:
def showModal(kopiUser: KopiUser): Unit = {
def modal = Modal().withTitle("modal title").
withBody(
p(s"${kopiUser.displayName}, please enter your data"),
Form(
FormInput.text("fieldlabel")
)
).
withButtons(
Modal.closeButton(),
Modal.button("Submit", Modal.dismiss)
)
modal.show()
}
When the user hits "Submit", I want to get the data that was entered and do something with it.
The dialog is animated, sliding and fading in and out as per bootstrap default, so I can't just register an onClick on the button, right?
How do I do this in a nice way - i.e. preferably some kind of bootstrap/scala.js kind of way, so that I retain my type safety?
I've looked in the bootstrap/scala.js project example, but that just displays an example dialog, it doesn't do anything with the data.
I've intentionally left off the bootstrap tag from this question, I'm looking for how to solve this with scala.js (via the bootstrap facade or not), rather than just using bootstrap itself.
This is modified example of object TestModal from bootstrap/scala.js v1.1.1. There are certainly also other ways to do this but one solution is to move field definitions out of the apply() and out of the form.
This way you can see and use them outside the TestModal2 object.
object TestModal2 {
val modalInputValue = Var("10000000") // Better use string
val radioGroup = FormInput.radioGroup(FormInput.radio("Test1", "modal-title", "First radio"), FormInput.radio("Test2", "modal-title", "Second radio"))
val select = FormInput.simpleSelect("Plain select", "Option 1", "Option 2", "Option 3")
val multipleSelect = FormInput.simpleMultipleSelect("Multiple select", "Option 1", "Option 2", "Option 3")
val inputTextArea = FormInput.textArea("Money text area", rows := 1, modalInputValue.reactiveInput)
val selectedFile = Var("")
val inputFile = FormInput.file("Test file", onchange := Bootstrap.jsInput { input ⇒
val file = input.files.head
selectedFile.update(file.name)
window.alert(s"File selected: ${file.name}")
})
val form = Form(
FormInputGroup(FormInputGroup.label("Money"), FormInputGroup.addon("usd".fontAwesome(FontAwesome.fixedWidth)), FormInputGroup.number(modalInputValue.reactiveInput)),
radioGroup,
select,
multipleSelect,
inputTextArea,
inputFile
)
def apply()(implicit ctx: Ctx.Owner): Modal = {
Modal()
.withTitle(radioGroup.value, " / ", select.selected.map(_.head), " / ", multipleSelect.selected.map(_.mkString(" + ")))
.withBody(p("You won ", modalInputValue, "$"), p(form))
.withButtons(Modal.closeButton(), Modal.button("Take", Modal.dismiss))
}
}
If you put somewhere in the calling code e.g. this
TestModal2.modalInputValue.trigger(
println("modalInputValue = " + TestModal2.modalInputValue.now)
)
TestModal2.select.selected.trigger(
println("select = " + TestModal2.select.selected.now)
)
TestModal2.selectedFile.trigger(
println("selectedFile = " + TestModal2.selectedFile.now)
)
You see the input value changes immediately on the console when they happen on the open dialog.
This is the answer I was given by the maintainer of the scalajs-bootstrap project.
def showModal(kopiUser: KopiUser): Unit = {
val data = Var("")
def modal = Modal().withTitle("modal title").
withBody(
p(s"${kopiUser.displayName}, please enter your data"),
Form(
FormInput.text("fieldlabel", data.reactiveInput)
)
).
withButtons(
Modal.closeButton(),
Modal.button("Submit", Modal.dismiss, onclick := Bootstrap.jsClick { _ ⇒
// Do something with input
window.alert(data.now)
})
)
modal.show()
}
To do what I wanted (including not closing the dialog when data was not entered), I had to additionally hack up the Modal facade class so that I could register onHide, onHidden events to not close the dialog, etc.

Scala Set different operations

So here is my code snippet:
val check = collection.mutable.Set[String]()
if (check.isEmpty) {
println("There is no transfer data available yet, please use the 'load' command to initialize the application!")
}
val userSelection = scala.io.StdIn.readLine("Enter your command or type 'help' for more information:")
val loadCommand = """^(?:load)\s+(.*)$""".r
userSelection match {
case loadCommand(fileName) => check add fileName ;print(check);val l= loadOperation(fileName);println(l.length); if (check.contains(fileName)){
programSelector()
}else{ loadOperation(fileName)}
So first of all I have an input with the match and one case is the "load" input.
Now my program is able to load different .csv files and store it to a List. However I want my program whenever it loads a new .csv file to check if it was loaded previously. If it was loaded before, it should not be loaded twice!!
So i thought it could work with checking with an Set but it always overwrites my previous fileName entry...
Your set operations are fine. The issue is the check add fileName straight after case loadCommand(fileName) should be in the else block. (One of those "d'oh" moments that we have now and then!?) :)
Update
Code
val check = collection.mutable.Set[String]()
def process(userSelection: String): String = {
val loadCommand = """^(?:load)\s+(.*)$""".r
userSelection match {
case loadCommand(fileName) =>
if (check.contains(fileName))
s"Already processed $fileName"
else {
check add fileName
s"Process $fileName"
}
case _ =>
"User selection not recognised"
}
}
process("load 2013Q1.csv")
process("load 2013Q2.csv")
process("load 2013Q1.csv")
Output
res1: String = Process 2013Q1.csv
res2: String = Process 2013Q2.csv
res3: String = Already processed 2013Q1.csv

Lift Framework - problems with passing url param to Snippet class

I am trying to do a simple case of /author/ and get the Lift to build a Person object based on the id passed in.
Currently i have an Author snippet
class Author(item: Person) {
def render = {
val s = item match { case Full(item) => "Name"; case _ => "not found" }
" *" #> s;
}
}
object Author{
val menu = Menu.param[Person]("Author", "Author", authorId => findPersonById(authorId), person => getIdForPerson(person)) / "author"
def findPersonById(id:String) : Box[Person] = {
//if(id == "bob"){
val p = new Person()
p.name="Bobby"
p.age = 32
println("findPersonById() id = " +id)
Full(p)
//}else{
//return Empty
//}
}
def getIdForPerson(person:Person) : String = {
return "1234"
}
}
What i am attempting to do is get the code to build a boxed person object and pass it in to the Author class's constructor. In the render method i want determine if the box is full or not and proceed as appropriate.
If i change
class Author(item: Person) {
to
class Author(item: Box[Person]) {
It no longer works but if i leave it as is it is no longer valid as Full(item) is incorrect. If i remove the val s line it works (and replace the s with item.name). So how do i do this. Thanks
The Box returned from findPersonById(id:String) : Box[Person] is evaluated and if the Box is Full, the unboxed value is passed into your function. If the Box is Empty or Failure the application will present a 404 or appropriate error page instead.
You can try double boxing your return if you want to handle this error checking yourself (so that the result of this method is always a Full Box).
def findPersonById(id:String) : Box[Box[Person]] = {
if(id == "bob"){
val p = new Person()
p.name="Bobby"
p.age = 32
println("findPersonById() id = " +id)
Full(Full(p))
}else{
return Full(Empty)
}
}
and then this should work:
class Author(item: Box[Person])