How to set conditions in jsf tags - jsf-1.2

can any one help on the below.
I need to open a new browser tab using command link tag in jsf, only when a condition is true.
How to set conditions in jsf tags?

You can either use the rendered attribute, and completing them with a EL expression. Using the rendered attribute, the link will only be shown if the condition is true.
If you want to open a commandlink in a new browser tab depending on a condition, you can easily achieve it using the rendered attribute:
<h:commandLink action="my_navigation_rule"
rendered="#{!MyBean.booleanValue}" />
<h:commandLink action="my_navigation_rule"
rendered="#{MyBean.booleanValue}" target="_blank"/>
As the rendered conditions are exclusionary, it will only be printed one of the commandLinks.
More info on JSF Expression Language (EL) (Very useful to set conditions in jsf tags) --> here
Note: I know the solution can be improved since you can use an EL expression to determine the target value, but in my opinion this solution is easier.

You can use managed bean actionListener of the commandMenu and then get the condition tested and redirect to the page in new tab if its true...
import javax.faces.event.ActionEvent;
public class PageBean {
String page;
public PageBean() {
}
public void getMenu(ActionEvent actionEvent) {
// Add event code here...
/* add your code to get and test condition and based upon the condition true and false conditon get commandMenu Id of the menu clicked by the following way
be sure to give the id of the command menu the same name you want to open in the next tab upon menu click like in my case i have given the command menu id as page1
String id = actionEvent.getComponent().getId();
System.out.println(" Menu ID : "+id);
now set the fetched menu id to the page variable with the proper page extension and acccess the pariable in the action from the manged bean to redirect to the page in the next tab upon menu click after testing the validation */
page = id;
System.out.println("Value assigned to the page from the menu Id is :"+page);
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public void dashContentEntryCheck(){
System.out.println("entered inside dashboard content task flow");
}
}

Related

How to use the Vaadin Testbench with Rich Text Area?

I am using Vaadin Testbench (4.1.0-alpha) for designing some integration test for my application (designed in Vaadin 7.6.1).
In a window, I use a rich test area. The idea is to design a test where the value of this rich text element is changed simulating some user behaviour. But now I realize I cannot find any method for change the value of this element, neither get the current value of the element.
I have tested some methods.getHTML() gets the HTML for the component, no the HTML of the designer. getText() gets the list of elements (font colour, background and other options of the element, but not the content).
Then I expect to have specific class methods for retrieving the value. If I explore the class RichTextAreaElement, seems that no method is implemented. All code in this class is:
#ServerClass("com.vaadin.ui.RichTextArea")
public class RichTextAreaElement extends AbstractFieldElement {
}
As you can see, no method is declared.
How can I do a test where a user change the value of this rich text area? It is not implemented?
Hmm yeah, that looks like some work in progress, probably because it's a complex component with all the features it provides. Nonetheless we can workaround the limitations a bit, again making use of chrome developer tools (or similar) and some custom classes to select the components by (actually it's just the gwt-RichTextArea).
Of course this serves just as a starting point and can be further enhanced. Also I'd be very interested to see a more elegant solution if someone finds one...
Structure inspection
Test class
public class RichTextAreaTest extends TestBenchTestCase {
#Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver", "D:\\Kit\\chromedriver_win32\\chromedriver.exe");
setDriver(new ChromeDriver());
}
#After
public void tearDown() throws Exception {
// TODO uncomment below once everything works as expected
//getDriver().quit();
}
#Test
public void shouldModifyRichTextArea() throws InterruptedException {
// class to identify the editor area by
String editorClass = "gwt-RichTextArea";
// open the browser
getDriver().get("http://localhost:8080/");
// select the first rich text
RichTextAreaElement richTextArea = $(RichTextAreaElement.class).first();
// get the editor section which is where we're writing
WebElement richTextEditorArea = richTextArea.findElement(By.className(editorClass));
// click inside to make it "editable"
richTextEditorArea.click();
// send some keystrokes
richTextEditorArea.sendKeys(" + something else added by selenium");
}
}
Result:
Update for getting the value
If you simply want to get the text, the code below will do the trick:
// switch to the editor iframe
getDriver().switchTo().frame(richTextEditorArea);
// get the <body> section where the text is inserted, and print its text
System.out.println("Text =[" + findElement(By.xpath("/html/body")).getText() + "]");
Output
Text =[Some predefined text + something else added by selenium]
At the end, I was able to obtain the content of the element selecting the first iframe of the page, and searching for the body content. The final code looks like:
String currentWindow = getDriver().getWindowHandle();
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
WebElement webelement = this.findElement(By.xpath("/html/body"));
String text = webelement.getText();
getDriver().switchTo().window(currentWindow);
return text;
As I need to switch between the iframe and the window, I am only able to obtain the content of the element, not the element itself. If I return directly the element for future use, an org.openqa.selenium.StaleElementReferenceException: Element belongs to a different frame than the current one - switch to its containing frame to use it exception is obtained.
For changing the text, the solutions is very similar, only use the sendKey functions to first remove existing characters and later add the new text:
String currentWindow = getDriver().getWindowHandle();
getDriver().switchTo().frame(getDriver().findElement(By.tagName("iframe")));
WebElement webelement = this.findElement(By.xpath("/html/body"));
// Remove any previous text.
String previousText = webelement.getText();
for (int i = 0; i < previousText.length(); i++) {
webelement.sendKeys(Keys.DELETE);
}
// Set text.
webelement.sendKeys(text);
getDriver().switchTo().window(currentWindow);

GWT CellList... when item clicked, previously clicked item loses its style

I have GWT CellList and after adding items via a DataProvider I use the following code to add styling to each item.
members... we can styling if a matched item is also in members
matched... passed in as a MetaJsArray<Contact>
CellList<Contact> list = getView().getResults();
for (int i=0; i<matched.length(); i++) {
if (members.isExistingEntry(matched.get(i))) {
list.getRowElement(i).addClassName("RED");
}
}
This code works until... I click items in the list.
onCellPreview() is called for each item clicked, but the previously clicked item loses its "RED" styling.
Do I need to add styling differently? Or how do I stop the loss of "RED"?
My guess its something to do the way GWT generates the javascript. When you manually set the cell on load its all good. When you select it, the javascript changes the object to use the selected CSS and when you un select it, the CSS changes to the default GWT CSS style for the cell.
Only way I can think of is to have a handler on select. When you select an item:
selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
public void onSelectionChange(SelectionChangeEvent event) {
// get item last selected
// check if needs re styling
// restyle
// do things with the new selected object
}
});
Add another check through the cell list and mark the ones that got unmarked.
This way might be inefficient, but its one way of avoiding your problem that I can think of. hope it helps.
After trying various approaches the only want that works, without hacks, is to define the style at the point of rendering.
With my own ContactCell extending AbstractCell the render() function can pass in a styling value into the contactcell.ui.xml file.
#Override
public void render(Context context, Contact value, SafeHtmlBuilder sb) {
if (value == null) {
return;
}
String styling = value.getStyling();
uiRenderer.render(sb, styling);
}
and then in contactcell.ui.xml file
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'>
<ui:with field='styling' type='java.lang.String'/>
<div class="{styling}"> ... </div>
GWT will mangle the style name so define your own CssResource class to access the class name thru so that the class name is mangled throughout the app.

asp.net mobile/desktop site toggle button, switching masterpage, but styles "stuck"

Summary
I'm having style issues when flipping master pages via a button event in asp.net 4.0. The new master switches, but the css from the old master remains. I don't understand how this could happen as the styles are defined within the head of the old master, and i can clearly see via the markup the new master is being displayed with whats supposed to be a totally different set of styles. Also, viewing source shows all the new css declarations in the head. How can i get this to "refresh" or "reload"?
Some details
I'm implementing a mobile version of my asp.net site. If a mobile device is detected i set a cookie and switch the master page in the preinit to a mobile friendly one. This works fine:
protected virtual void Page_PreInit(Object sender, EventArgs e)
{
if (IsMobile)
this.Page.MasterPageFile = "m-" + this.Page.MasterPageFile;
}
I have a "full site" button at the bottom that allows you to flip back and forth between the mobile and desktop view. When clicking it, i change the value in the cookie. Then when the page redirects to itself, the value is checked, and it gives the respective masterpage. This also "works", i can tell the right masterpage is rendering via markup. Except the styles from the mobile version remain even when the desktop master is being displayed. I did the redirect thinking it would prevent this.
// desktop/mobile site toggle button click event
protected void viewMobileButton_Click(Object sender, EventArgs e)
{
HttpCookie isMobileCookie = Cookies.snatchCookie("isMobile");
if (bool.Parse(isMobileCookie.Value))
Cookies.bakeCookie("isMobile", "false");
else
Cookies.bakeCookie("isMobile", "true");
Response.Redirect(Request.RawUrl);
}
This is the first time I've done anything like this, and not sure if i'm even going about it the right way, or how to debug from here. Thanks in advance for any help.
Edit
Ok, so i figured out it's related to the JQuery Mobile Scripts. JQuery Mobile has this way of tying pages together. I don't fully understand it, i think they use it for page transitions, and it's preventing my new CSS from registering. When i turn it off, my masterpage flips fine with css included. I'm looking into a way to turn off JQuery Mobile before my redirect. Note sure how though yet.
The problem ended up being related to JQuery Mobile AJAX for page-transitions. JQuery Mobile does not load the head of the document on additional page requests after the first.
So when i'd switch the mobile master to the desktop master, the head of the document wouldn't load to bring in my styles. There are a few way's this can be fixed:
This way just turns off AJAX altogether, and fixes the problem, but then you can't benefit from it:
<form data-ajax="false">
This is a way to do it problematically, but remind you, it will not work via an event after initialization of JQuery Mobile, so again you can't benefit from it:
$.mobile.ajaxEnabled = false;
The above two solutions i support could work if you redirected through a page first if you have to use an onclick event and an event handler.
A better solution is to add rel="external" to the link to tell JQM it's and outgoing link.
<a href="myself.com?mobile=true" rel="external" >
But because i couldn't run some code i wanted to in order to change the cookie, i had to pass a query string parameter, check it on the preinit, then set the cookie which my page also looks at on the preinit and flips the master.
Here's my full solution below in case someone is out there doing the exact same thing. Note because my website is using aliasing, i had to read Request.RawUrl and parse it myself since the Request.QueryString object did not contain the values i passed.
// reusable function that parses a string in standard query string format(foo=bar&dave=awesome) into a Dictionary collection of key/value pairs
// return the reference to the object, you have to assign it to a local un-instantiated name
// will accept a full url, or just a query string
protected Dictionary<string, string> parseQueryString(string url)
{
Dictionary<string, string> d = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(url))
{
// if the string is still a full url vs just the query string
if (url.Contains("?"))
{
string[] urlArray = url.Split('?');
url = urlArray[1]; // snip the non query string business away
}
string[] paramArray = url.Split('&');
foreach (string param in paramArray)
{
if (param.Contains("="))
{
int index = param.IndexOf('=');
d.Add(param.Substring(0, index), param.Substring(++index));
}
}
}
return d;
}
Then i just use my dictionary object to evaluate and rebuild my url with the opposite mobile value, dynamically setting the href on the toggle link. Some code is obviosuly left out, but for perspective, base._iPage.QueryStringParams hold my dictionary object that was returned, and base._iPage.IsMobile is just a bool property i also have via the page interface i use, that all my pages, and user controls, ect, can talk to.
// get the left side fo the url, without querystrings
StringBuilder url = new StringBuilder(Request.RawUrl.Split('?')[0]);
// build link to self, preserving query strings, except flipping mobile value
if (base._iPage.QueryStringParams.Count != 0)
{
if (base._iPage.QueryStringParams.ContainsKey("mobile"))
{
// set to opposite of current
base._iPage.QueryStringParams["mobile"] = (!base._iPage.IsMobile).ToString();
}
int count = 0;
url.Append('?');
// loop through query string params, and add them back on
foreach (KeyValuePair<string, string> item in base._iPage.QueryStringParams)
{
count++;
url.Append(item.Key + "=" + item.Value + (count == base._iPage.QueryStringParams.Count ? "" : "&" ));
}
}
// assign rebuild url to href of toggle link
viewMobileButton.HRef = url.ToString();
}
Then on my pageinit this is where i actually check, first the quesry string, then the cookie, if neither of those are present, i run my mobile detection method, and set a cookie, and my interface bool property for easy access to conditionals that depends on it.
QueryStringParams = base.parseQueryString(Request.RawUrl);
if (QueryStringParams.ContainsKey("mobile") ? QueryStringParams["mobile"].ToLower().Equals("true") : false)
{
Cookies.bakeCookie("isMobile", "true"); // create a cookie
IsMobile = true;
}
else if (QueryStringParams.ContainsKey("mobile") ? QueryStringParams["mobile"].ToLower().Equals("false") : false)
{
Cookies.bakeCookie("isMobile", "false"); // create a cookie
IsMobile = false;
}
else
{
IsMobile = base.mobileDetection();
}
if (IsMobile)
this.Page.MasterPageFile = "m-" + this.Page.MasterPageFile;
}

Full text search in the Attached documents in Kentico CMS 7

Is there any way in which I can search the attachments and show the attached documents in the search result? My search result should show only the attachments in which the search text is contained. Right now I can search the attachments and the page in which the attachment contains search text is shown.
Say, I have a Page Home and attachment myattachment.docx as its attachment. While searching Background as search text in the Site search, which is contained only in the myattachment.docx (not contained in Home page) , the search result show Home page as a search result. What I am intending is to return something like Home/ myattachment.docx as a result instead of Home page. My page may any number of attachments.
Thanks In Advance!
The info on this is a little bit sketch. See below for the documentation I used.
Create a custom global event handler in AppCode (or Old_App_Code), make sure it is a partial class of CMSModule Loader.
Add your custom event handler in the overriden Init() The one you want is DocumentEvents.GetContent.Execute.
The sender object should be the current TreeNode being indexed for search. You can then use that node to access the relevant attachments and modify the event args e.content to add your document text to the search.
[CustomDocumentEvents]
public partial class CMSModuleLoader
{
private class CustomDocumentEventsAttribute : CMSLoaderAttribute
{
public override void Init()
{
// Assigns custom handlers to the appropriate events
DocumentEvents.GetContent.Execute += Document_GetContent;
}
private void Document_GetContent(object sender, DocumentEventArgs e)
{
TreeNode node = sender as TreeNode;
if (node != null)
{
//Note, this is psuedo code, this isnt the way to iterate over TreeNode.Attachments
foreach( attachment in node.Attachments ) {
e.Content += attachment.content;
}
}
}
}
}
More info
See http://devnet.kentico.com/docs/devguide/index.html?event_handlers_overview.htm for implementing custom events in general in version 7.
See this for custom search in version 5
http://devnet.kentico.com/Knowledge-Base/Search/How-to-search-for-documents-using-assigned-categor.aspx
See http://devnet.kentico.com/Knowledge-Base/API-and-Internals/Custom-Handler-Library-compatibility.aspx for the updated event name for version 7 referred to in the version 5 custom search example.

How to update an iFrame in Visualforce

I have an iFrame that is similar to the following:
<apex:iframe src="http://www.salesforce.com" scrolling="true" height="600" width="100%" id="docframe"/>
I would like to use a link on the parent page (that contains the iFrame) to update the content of the iFrame.
I tried using code similar to whats presented in the iFrame Target example on here: http://www.w3schools.com/html/html_iframe.asp but on my browser (Firefox) it opens a new tab. Even when I copy and paste the example from the preceding link into my visualForce page it insists on opening a new tab in my browser.
Any idea on what I may want to try to get this to work?
I would do it this way
1) First define the SRC of your iFrame in apex and implement the reload method:
public with sharing class YourClass {
// Source var for the iFrame
public String iframeSource { get; set; }
// Constructor
public YourClass() {
// Default value of the frame source
iframeSource = 'apex/Page1';
}
// The method to reload the iframe with another source page
public PageReference reloadIframe() {
iframeSource = 'apex/Page2';
return null;
}
}
2) Now create a command button to reload the iFrame and the pannel to be refreshed:
<apex:commandButton action="{!reloadIframe}" reRender="theFrame"/>
<apex:outputPanel id="theFrame">
<apex:iframe src="{!iframeSource}" />
</apex:outputPanel>

Resources