Primefaces handler to penult tab - java

I decided to use wizard component.link on this component
I have condition that instead of checkbox "Skip to last" I should use button. If I press on this button it's ok, but when I go to penult tab I want generate content of confirmation tab,
public void generatePreview() {
for (CompetitionTypeBean competitionType : competitionTypeList) {
if (competitionType.getId().equals(competitionTypeId)) {
tournamentBean.setCompetitionTypeBean(competitionType);
}
}
if (teamList != null && !teamList.isEmpty()) {
List<TeamBean> teams = new ArrayList<TeamBean>();
for (TeamBean team : teamList) {
for (Long teamId : teamListSelected)
if (team.getId().equals(teamId)) {
teams.add(team);
break;
}
}
tournamentBean.setTeams(teams);
}
}
it means that I should set skip in true for that I decide to write js function which will work on onnext event of wizard
<script type="text/javascript">
function setHiddenValue(formId, componentId, new_value) {
var tabId = 'competitionId';
if (tabId != 'predLast') {
document.getElementsByName('wiz').next();
} else {
var fullComponentId = formId + ":" + componentId;
document.getElementById(fullComponentId).value = new_value;
}
}
</script>
And there I find new problem
First I don't know as I can get current Tab Id. And second I don't how with help js make next event for wizard document.getElementsByName('wiz').next();. I try to see generated html code. Every tab is <li> and when this tab is selected in css style that li add 'ui-state-hightlight'
Maybe I try to develop cycle. But I can't find other solution.

To get the index of the current step in javascript, use the getStepIndex() function. To get name of the current step in the backing bean, you need to obtain a reference to the Wizard in your view and either call getStep()(returns the id property of the next tab) or getStepToProcess()(returns the actual next Tab object, from which you can get the name of the current tab).
<p:wizard/> has onnext and onback event callbacks that you can hook into to process javascript (or backing bean code with <p:remoteCommand/>)

I just add next rows in handler
public String onFlowProcess(FlowEvent event) throws Exception {
if ((skip == true)) {
skip = false; //reset in case user goes back
generatePreview();
return CONFIRM_TAB_ID;
} else {
String newTab = event.getNewStep();
if (CONFIRM_TAB_ID.equals(newTab)) {
generatePreview();
}
return newTab;
}
}
I think that using constant CONFIRM_TAB_ID it's normal, because I never decide to change this tabId.

Related

Vaadin: How to set validation false to form from listener

I have a form and some textfields on it:
TextField taxNumber = new TextField();
taxNumber.setPrefixComponent(VaadinIcon.BARCODE.create());
accountApplicationBinder
.forField(taxNumber)
.withValidator(new StringLengthValidator(....
And I have some validation logic in the Listener:
taxNumber.addBlurListener(event -> {
String localResult = "";
InfoResult ir = ks.loadInfo(taxNumber.getValue());
if ((ir.errorText == null) && (!ir.name.isEmpty())) {
...
} else {
localResult = "";
taxNumber.setInvalid(true);
taxNumber.setErrorMessage("Not valid tax - " + accountApplicationBinder.isValid());
}
taxNumberStatusLabel.setText(localResult);
});
And I want to get a behavior like a ".withValidator... return not valid" in my submit button listener. In other words: I want to have my submit button not working then taxNumber.addBlurListener return not valid result. How I can do that?
it seems to me that your logic in the blurlistener replicates the validation you have already set when you bound the field with .withValidator(new StringLengthValidator()). That Validator is supposed to do exactly that.
When you click your submit button, all you have to do is validate the binder, and if it's not valid, then don't submit. You can customize the error string that it shows under the taxNumber field by providing a customized string into the StringLengthValidator:
.withValidator(new StringLengthValidator("Not valid tax", 4, null))
I just realized that you probably have custom validation in ks.loadInfo(taxNumber.getValue()). If that is the case, then the best way is to replace the StringLengthValidator with a custom Validator that you can write, for example like this
.withValidator(taxNr -> {
InfoResult ir = ks.loadInfo(taxNr);
return ir.errorText == null && !ir.name.isEmpty();
}, "Not valid tax")

Button.isEnabled() returns true even though the button is disabled by default [duplicate]

This question already has answers here:
Button enabled or disabled : How does webdriver decide?
(2 answers)
Closed 5 years ago.
While testing I got a road block where I have a button in a WebPage which is disabled by default. I am using Selenium WebDriver to test if the button is disabled by default the boolean is always returning true.
Boolean buttonStatus = (button XPath).isEnabled
It will be great if someone can help me
HTML Information:
<div class="commandbutton commandbutton--theme-disabled commandbutton--recommended">
<button class="commandbutton-button commandbutton-button--disabled" type="button" tabindex="-1">
From isEnabled docs
This will generally return true for everything but disabled input
elements.
But it will work on buttons as well. However, isEnabled() checks for the disabled attribute. If the button is disabled by JavaScript or any other means isEnabled() won't detect it.
My guess is the button has other classes when it is enabled or disabled. For example, when enabled it probably won't have commandbutton-button--disabled class. You can check for it
WebElement button = driver.findElement(By.xpath("button XPath"));
String classes = button.getAttribute("class");
boolean isDisabled = classes.contains("commandbutton-button--disabled");
I had the same problem. But my elements on the page were very strange. Some of them selenium could click although they were not clickable, some of them selenium couldn't click, but could send keys to them. After a few hours of thinking, I have wrote universal method, that checks if elements is enabled or not.
After talking with programmer, I have known, that they use on this page some special Select, and it looks like Div with Input in it. And he says, that I can check it disabling by checking attribute Class of Div. If there is 'select2-container-disabled' then this Input is disabled.
And I change my method. Now it looks like that:
public boolean isNotClickable(WebElement... elements) {
List<WebElement> elementsChecked = new ArrayList<>();
List<WebElement> elementsToCheckByClass = new ArrayList<>();
List<WebElement> elementsToCheckByClick = new ArrayList<>();
List<WebElement> elementsToCheckBySendKeys = new ArrayList<>();
for (WebElement checkedElement : elements) {
log.info("Checking, that element [" + getLocator(checkedElement) + "] is not clickable by isEnabled()");
if (checkedElement.isEnabled()) {
elementsToCheckByClass.add(checkedElement);
} else {
elementsChecked.add(checkedElement);
}
}
if (!elementsToCheckByClass.isEmpty()) {
for (WebElement checkedByClassElement : elementsToCheckByClass) {
log.info("Checking, that element [" + getLocator(checkedByClassElement) + "] is not clickable by class");
String classOfElement = checkedByClassElement.getAttribute("class");
List<String> classes = new ArrayList<>(Arrays.asList(classOfElement.split(" ")));
if (!classes.contains("select2-container-disabled")) {
elementsToCheckByClick.add(checkedByClassElement);
} else {
elementsChecked.add(checkedByClassElement);
}
}
}
if (!elementsToCheckByClick.isEmpty()) {
WebDriverWait wait = new WebDriverWait(driverUtils.getDriver(), 1);
for (WebElement checkedByClickElement : elementsToCheckByClick) {
log.info("Checking, that element [" + getLocator(checkedByClickElement) + "] is not clickable by clicking it");
try {
wait.until(elementToBeClickable(checkedByClickElement));
elementsToCheckBySendKeys.add(checkedByClickElement);
} catch (Exception e) {
elementsChecked.add(checkedByClickElement);
}
}
}
if (!elementsToCheckBySendKeys.isEmpty()) {
for (WebElement checkedBySendKeysElement : elementsToCheckBySendKeys) {
log.info("Checking, that element [" + getLocator(checkedBySendKeysElement) + "] is not clickable by sending keys");
try {
checkedBySendKeysElement.sendKeys("checking");
return false;
} catch (Exception e) {
elementsChecked.add(checkedBySendKeysElement);
}
}
}
return elementsChecked.size() == elements.length;
}
isEnabled can only tell you the button works fine, you need to check the class attribute to check is the button is enabled.

Javascript function Wicket test

I have an ajaxEditableLabelWithIcon which is a ajaxEditableLabel with a modified HTML that contain an icon. When the user click this icon, the editor field become editable and when he click again, the content is saved. We did that using JQuery :
function editOrSubmit(element){
panel = element.parentElement;
label = panel.children[0];
if(panel.find){
e = $.Event('keypress');
e.which = 13; // Enter key
label.trigger(e); //submit the FormTester
}
else{
label.click(); //Wich make the label editable
}
}
Now, I want to test it using JUnit. Since I can't directly click on the icon, I tried to create a javascript shortcut to the function, and then create a Robot to trigger the KeyPressed events :
// defining flags
var isCtrl = false;
var isShift = false;
$(document).ready(function() {
// action on key up
$(document).keyup(function(e) {
if(e.which == 17) {
isCtrl = false;
}
if(e.which == 16) {
isShift = false;
}
});
// action on key down
$(document).keydown(function(e) {
if(e.which == 17) {
isCtrl = true;
}
if(e.which == 16) {
isShift = true;
}
// En cas d'appui sur ctrl+Shift+F9 en même temps, la méthode editOrSubmit est appelée
if(e.which == 120 && isCtrl && isShift) {
var icon = document.getElementById("icon");
editOrSubmit(icon);
}
});
});
It work well in a browser, but inside the test nothing happen ? Do you know why ?
unfortunately Wicket and JUnit cannot test JavaScript code but just Java code. However, Wicket itself uses Maven and frontend-maven-plugin to run QUnit tests via Maven. You can take a look at Wicket code inside testing/wicket-js-tests (https://github.com/apache/wicket/tree/master/testing/wicket-js-tests) to see how this is done by Wicket and you can copy the code you need to run your tests.

WebDriver is unable to perform click on an input element having onclick=function1() as an attribute

I am using Web driver 2.31 with Java. It seems the web driver is unable to perform click action on an input element having onclick() attribute.
The input element I need to perform click action on is having the following attributes - id (which is a random generated number), class, type=button, onclick, onmouseout, onmouseover, title and value.
I'm able to fetch the values of title and value attributes which means that the web driver is able to recognize the input element but is not able to perform click action on it.
I have tried with the following:
webdriver.findElement(By.xpath("xpath for the input")).click()
webdriver.findElement(By.xpath("xpath for the input")).sendKeys(Keys.ENTER);
new Actions(webdriver).moveToElement(webdriver.findElement(By.xpath("xpath for the input"))).click().perform();
None of the above options are working.
Do you get any exceptions from element.click()? It it enabled and visible? One of the problems we had was that WebDriver didn't handle position:static elements correctly, so during playback it would cover the button (and you won't see it on screenshot) and it would throw exception "Element is not clickable at point".
We had similar problem with element and had following code that did work sometimes (but also not 100% of times):
element.click();
if("button".equals(tagName)) {
if(element.isEnabled() && element.isDisplayed())
element.sendKeys(Keys.ENTER);
}
But the problem disappeared itself after upgrading WebDriver and we removed sendKeys(ENTER), also it was working fine in 2.29.0.
I faced exactly same problem in my project. The issue was not to locate the element but the onClick() event was not firing.
Then i found out that something else was there which stopped from the event to fire. I had used java script to enable the date picker box & did this,
((JavascriptExecutor)driver).executeScript ("document.getElementById('txtOriginDate').removeAttribute('readonly',0);");
WebElement originDateBox= driver.findElement(By.xpath(prop.getProperty("originDateBox")));
originDateBox.clear();
originDateBox.sendKeys("9-Dec-2014"); //Enter date
Developer designed this in such a way that if you don't use date picker to select date, a specific variable was not set. Which eventually made the **onclick event not to fire.
The date picker code was something like this,
var jsoncustdate = "";
var jsonorigindate = "";
function onSelectCalender( StrDt, obj )
{
if ( !varReadonly ) {
if ( $( "#txtCustDescisionDate" ).attr( "IsDisable" ) == "FALSE" )
{
if ( obj.id == "txtCustDescisionDate" )
{
custobjDt = new Date( obj.selectedYear, obj.selectedMonth,obj.selectedDay, 0, 0, 0, 0 );
jsoncustdate = custobjDt.getTime();
jsoncustdate = "\/Date(" + jsoncustdate + ")\/";
DisabledBtnStage();
// $("#txtFromDate").datepicker("option", "maxDate", objDt);
}
if ( obj.id == "txtOriginDate" )
{
var objDt = new Date( obj.selectedYear, obj.selectedMonth,obj.selectedDay,0, 0,0,0 );
jsonorigindate = objDt.getTime();
jsonorigindate = "\/Date(" + jsonorigindate + ")\/";
DisabledBtnStage();
// $("#txtToDate").datepicker("option", "minDate", objDt);
}
}
elogCommon.CheckMandatory();
}
}
I finally used date picker in normal way & the event fired smoothly.
I hope this answer will help . .cheers !!!

Can I trigger an IceFaces action using JavaScript?

If I have a simple button:
<ice:panelGroup>
<ice:commandButton value="foobar"
action="#{fileManager.openNoFlashVisiblePopup}" />
</ice:panelGroup>
Is it possible to trigger the action openNoFlashVisiblePopup using just javascript? I know that there IceFaces has a JavaScript bridge but I don't know see a simple way to do just this.
i need to do this because I have a chunk of JavaScript that detects Flash and I need to show a IceFaces popup.
One way is to get the button element by ID and call its click() function.
document.getElementById('clientId').click();
You only need to give the form and button a fixed id so that you can use the generated HTML ID as clientId in Javascript code.
I know I'm a little late in seeing this, but the correct way to handle this (minus perhaps the overly exhuberant error checking) is:
// There's a <div> that looks like: <div class="portletfaces-bridge-body" id="A8660">.
// We'll find it and pull out the value of the ID to build elementId like: A8660:wtfForm:editeventparent
var div = null;
var divCollection = document.getElementsByTagName("div");
for (var i=0; i<divCollection.length; i++) {
if(divCollection[i].getAttribute("class") == "portletfaces-bridge-body") {
div = divCollection[i];
break;
}
}
if (div == null){
alert("could not find div portletfaces-bridge-body.");
return;
}
// Pull the id out of divInnerText.
var id = div.getAttribute("id");
if (id == null){
alert("id was null");
}
// prepare initializes fields to null so rendered cannot begin until both itemId and parentId are set.
var prepare = document.getElementById(id + ":wtfForm:editeventprepare");
if (prepare == null){
alert("editeventprepare element was not found.");
return;
}
prepare.click();

Categories

Resources