I have a <h:commandButton> on my page connected with action in my bean. It work just fine, but I wanted to add confirmation message. When I used:
<h:commandButton onclick="confirm('Are you sure?')">
it alco works just fine. But when I try to get string from bean, by making it looks like this:
<h:commandButton onclick="confirm('#{bean.confirmQ}')"> it doesn't display this string. In getter for this string I invoke method to take some info from DB, and I format it then I return it. When I use this approach nothing is shown, not even empty box, and page looks like just refreshing.
Here is code from bean:
private String confirmQ;
public String getConfirmQ() {
WycenioneAuta wa = getWycenioneAuto();
String question = "are you sure \n" + wa.getName + "?";
confirmQ = question;
return confirmQ;
}
public void setConfirmQ(String confirmQ) {
this.confirmQ = confirmQ;
}
Escape the line by writing String question = "are you sure \\n" + wa.getName + "?";
If your String variable is confirmQ , then the right EL pointing to that variable is #{bean.confirmQ} and not #{bean.confirm} as you've written.
In complement to ஜன்'s Answer:
At least for Firefox , I should had a return in the Javascript code, otherwise the cancel does not work:
<h:commandButton onclick="return confirm('Are you sure?')" ... />
Related
I'm pretty new to Java so bear with me. I have a scriptlet that
is put into a JSTL tag. I'm trying to do away with my scriptlets
and put them in a seperate class. Except I'm really stumped on this
one. I have a pretty basic Java method:
static final String default = "Enter a message";
String subDate(String out){
final String year = "" + Calendar.getInstance().get(Calendar.YEAR);
return out.replaceAll("%CURRYEAR%", year);
}
In my JSTL I call it like below
<c:out value="<%= subDate(msg) %>" default="<%= subDate(default) %>"
When I'm converting this to my Java class this is what I have. But I'm
simply not getting anything. I'm also really confused on how I would
pass it multiple parameters like I'm doing in my JSTL.
public String getsubDate(String in){
return in.replaceAll("%CURRYEAR%", YEAR) + getMsg();
}
Any help is greatly appreciated!
Since it sounds like you're putting msg on the request in the servlet using request.setAttribute, you can get the correct year in the servlet, replace all occurances of %CURRYEAR% right there and just put the correct message on the request:
String year = "" + Calendar.getInstance().get(Calendar.YEAR);
request.setAttribute("msg", msg.replaceAll("%CURRYEAR%", year));
Then on your page just do this:
<c:out value="${msg}" />
I am learning play framework and understand that I can map a request such as /manager/user as:
GET /manage/:user Controllers.Application.some(user:String)
How would I map a request like /play/video?video_id=1sh1?
You have at least two possibilities, let's call them approach1 and approach2.
In the first approach you can declare a routes param with some default value. 0 is good candidate, as it will be easiest to build some condition on top of it. Also it's typesafe, and pre-validates itself. I would recommend this solution at the beginning.
Second approach reads params directly from request as a String so you need to parse it to integer and additionally validate if required.
routes:
GET /approach1 controllers.Application.approach1(video_id: Int ?=0)
GET /approach2 controllers.Application.approach2
actions:
public static Result approach1(int video_id) {
if (video_id == 0) return badRequest("Wrong video ID");
return ok("1: Display video no. " + video_id);
}
public static Result approach2() {
int video_id = 0;
if (form().bindFromRequest().get("video_id") != null) {
try {
video_id = Integer.parseInt(form().bindFromRequest().get("video_id"));
} catch (Exception e) {
Logger.error("int not parsed...");
}
}
if (video_id == 0) return badRequest("Wrong video ID");
return ok("2: Display video no. " + video_id);
}
PS: LOL I just realized that you want to use String identifier... anyway both approaches will be similar :)
I would do it simply using:
GET /play/video Controllers.Application.video(video_id:String)
And at controller you would of course have, something like:
public static Result video(String video_id) {
return ok("We got video id of: " + video_id);
}
Alternatively, you dont have to add video_id:String since play seems to treat parameters as String by default, so it also works like this (at least with newest play):
GET /play/video Controllers.Application.video(video_id)
Typing localhost:9000/play/video?video_id=1sh1 to address bar should now you give view which prints:
We got video id of: 1sh1
To add more parameters is simple, like this:
GET /play/video controllers.Application.video(video_id:String, site:String, page:Integer)
Controller:
public static Result video(String video_id, String site, Integer page) {
return ok("We got video id of: " + video_id + " site: " + site + " page: " + page);
}
Typing localhost:9000/play/video?video_id=1as1&site=www.google.com&page=3 to address bar should now you give view which prints:
We got video id of: 1as1 site: www.google.com page: 3
You're welcome ^^.
I'm not quite sure if I got what you meant if you meant just to map a url to function in controller the answer of biesior is perfect but if you mean submitting a form with get method like
#helper.form(action = routes.YourController.page1()) {
}
and having the form's parameter in the url in the url-rewrited format like
page1/foo/bar instead of page1?param1=foo¶m2=bar
There is no way to do that because that's http specs
I do often circumvent this limitation by getting the parameters in the first function in controller and then redirect them to another view just like the following
public static Result page1(){
String param1 = Form.form().bindFromRequest().get("param1");
String param2= Form.form().bindFromRequest().get("param2");
return ( redirect( routes.YourController.page2(param1,param2)));
}
Then have whatever in the page2
public static Result page2(String param1,String param2){
...............
}
And have this in the routes file :
GET page2/:param1/:param2 controllers.YourControllers.page2(param1 : String, param2 : String )
I hope it'd help but I'm not sure that's the best practise
Ok so I just read up the documentation and what I understand is that you need to
GET /play/video Controllers.Application.video()
And then in the controller call the getQueryString of the HttpRequest object
http://www.playframework.com/documentation/api/2.1.0/java/index.html
I got some troubles with some codes. Now I try to modify/delete personal information , but I enter an invalid value try modify/delete , it's still pop a new window . I dont know how to modify those code for i enter an invalid value , it will not pop a window .
I have other question . When I enter a valid value , the value cant pass to pop window , like I enter a name to go grab id value , the value cant pass to pop window , how can I reslove it . Thank all !
HTML
<h:panelGrid columns="3" cellspacing="20">
<h:outputLabel for="name" value="Modify Name"/> <p:inputText value="#{modify.enName}"/>
<h:commandButton value="Modify System" style="height:35px" onclick="window.open('#{modify.domodify()}','modify',
'width=500,height=400,status=yes,resizable=yes,scrollbars=yes') ; return false;"/>
</h:panelGrid>
Java Code
public String domodify() {
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.mycompany_SuneCoolingSystem_war_1.0-SNAPSHOTPU");
EmployeeJpaController jpaController = new EmployeeJpaController(null, emf);
EntityManager e = jpaController.getEntityManager();
Query q = e.createNamedQuery("Employee.findByEnName");
q.setParameter("enName", getEnName());
System.out.println(getEnName());
List resultList = q.getResultList();
Employee result = (Employee) resultList.get(0);
id = result.getId();
name = result.getName();
idNumber = result.getIdNumber();
constellation = result.getConstellation();
email = result.getEmail();
enName = result.getEnName();
rego="CRUD/Modify.xhtml";
} catch (Exception ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "No Man", ""));
rego = "index.xhtml";
}
return rego;
}
onclick="window.open('#{modify.domodify()}','modify', 'width=500,height=400,status=yes,resizable=yes,scrollbars=yes')
This code means when clicked, open a new window and perform the action to check what URL is returned. The windows is opened before any logic is executed.
You should perform an ajax call to the modify with f:ajax (or your component library equivalent, if you want) and use onevent to launch the correct javascript when the ajax calls ends in success and returning the expected value.
See JSF 2: How show different ajax status in same input? to see an example of dealing with onevent.
I'm trying to use Selenium WebDriver to input text to a GWT input element that has default text, "Enter User ID". Here are a few ways I've tried to get this to work:
searchField.click();
if(!searchField.getAttribute("value").isEmpty()) {
// clear field, if not already empty
searchField.clear();
}
if(!searchField.getAttribute("value").isEmpty()) {
// if it still didn't clear, click away and click back
externalLinksHeader.click();
searchField.click();
}
searchField.sendKeys(username);
The strange thing is the above this only works some of the time. Sometimes, it ends up searching for "Enter User IDus", basically beginning to type "username" after the default text -- and not even finishing that.
Any other better, more reliable ways to clear out default text from a GWT element?
Edited to add: The HTML of the input element. Unfortunately, there's not much to see, thanks to the JS/GWT hotness. Here's the field when it's unselected:
<input type="text" class="gwt-TextBox empty" maxlength="40">
After I've clicked it and given it focus manually, the default text and the "empty" class are removed.
The JS to setDefaultText() gets called both onBlur() and onChange() if the change results in an empty text field. Guess that's why the searchField.clear() isn't helping.
I've also stepped through this method in debug mode, and in that case, it never works. When run normally, it works the majority of the time. I can't say why, though.
Okay, the script obviously kicks in when the clear() method clears the input and leaves it empty. The solutions it came up with are given below.
The naïve one, presses Backspace 10 times:
String b = Keys.BACK_SPACE.toString();
searchField.sendKeys(b+b+b+b+b+b+b+b+b+b + username);
(StringUtils.repeat() from Apache Commons Lang or Google Guava's Strings.repeat() may come in handy)
The nicer one using Ctrl+A, Delete:
String del = Keys.chord(Keys.CONTROL, "a") + Keys.DELETE;
searchField.sendKeys(del + username);
Deleting the content of the input via JavaScript:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value = '';", searchField);
searchField.sendKeys(username);
Setting the value of the input via JavaScript altogether:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].value = '" + username + "';", searchField);
Note that javascript might not always work, as shown here: Why can't I clear an input field with javascript?
For what it is worth I'm have a very similar issue. WebDriver 2.28.0 and FireFox 18.0.1
I'm also using GWT but can reproduce it with simple HTML/JS:
<html>
<body>
<div>
<h3>Box one</h3>
<input id="boxOne" type="text" onfocus="if (this.value == 'foo') this.value = '';" onblur="if (this.value == '') this.value = 'foo';"/>
</div>
<div>
<h3>Box two</h3>
<input id="boxTwo" type="text" />
</div>
</body>
</html>
This test fails most of the time:
#Test
public void testTextFocusBlurDirect() throws Exception {
FirefoxDriver driver = new FirefoxDriver();
driver.navigate().to(getClass().getResource("/TestTextFocusBlur.html"));
for (int i = 0; i < 200; i++) {
String magic = "test" + System.currentTimeMillis();
driver.findElementById("boxOne").clear();
Thread.sleep(100);
driver.findElementById("boxOne").sendKeys(magic);
Thread.sleep(100);
driver.findElementById("boxTwo").clear();
Thread.sleep(100);
driver.findElementById("boxTwo").sendKeys("" + i);
Thread.sleep(100);
assertEquals(magic, driver.findElementById("boxOne").getAttribute("value"));
}
driver.quit();
}
It could just be the OS taking focus away from the browser in a way WebDriver can't control. We don't seem to get this issue on the CI server to maybe that is the case.
I cannot add a comment yet, so I am putting it as an answer here. I want to inform you that if you want to use only javascript to clear and/or edit an input text field, then the javascript approach given by #slanec will not work. Here is an example: Why can't I clear an input field with javascript?
In case you use c# then solution would be :
// provide some text
webElement.SendKeys("aa");
// this is how you use this in C# , VS
String b = Keys.Backspace.ToString();
// then provide back space few times
webElement.SendKeys(b + b + b + b + b + b + b + b + b + b);
I want to validate the inputs to my JSF page inside my Managed bean, but for some reason it does not work?
#ManagedBean
#RequestScoped
public class RegistrationController {
//values passed from the JSF page
private String name;
...
public void validateName(FacesContext context, UIComponent validate,
Object value) {
String inputFromField = (String) value;
String simpleTextPatternText = "^[a-zA-Z0-9]+$";
Pattern textPattern = null;
Matcher nameMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
nameMatcher = textPattern.matcher(getName());
if (!nameMatcher.matches()) {
((UIInput) validate).setValid(false);
FacesMessage msg = new FacesMessage(
"your name cant contain special characters");
context.addMessage(validate.getClientId(), msg);
}
}
This is how input component looks like(Inside a form):
<h:inputText value="#{registrationController.name}" validator="#{registrationController.validateName}" required="true">
<h:message for="nameInput"/>
When i enter a wrong input i dont see the validation message, and in the console i see this:
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.
sourceId=bRegForm:j_idt7[severity=(ERROR 2), summary=(bRegForm:j_idt7: Validation Error: Value is required.), detail=(bRegForm:j_idt7: Validation Error: Value is required.)]
What it could be? Am i forgetting something? Do i have to add something to my configuration files...?
You forgot to give your input component an id. That's where the for attribute of <h:message> should point to.
<h:inputText id="nameInput">
Unrelated to the concrete problem, your approach is clumsy and technically wrong. As per the specification, you should throw a ValidatorException. So instead of
((UIInput) validate).setValid(false);
context.addMessage(validate.getClientId(), msg);
do
throw new ValidatorException(msg);
Then JSF will worry about setting the component as invalid and adding the message to the context.
There's a second problem, you're validating the local value instead of the submitted value.
Replace
nameMatcher = textPattern.matcher(getName());
by
nameMatcher = textPattern.matcher(inputFromField);