SelectOneMenu not displayed correctly - java

I would appreciate some input on the following issue:
I got one login screen followed by another page with a Panel and inside this Panel a SelectOneMenu. Unfortunatly the output of the SelectOneMenu after login is sometimes like this:
Instead the full(!) name of the User should be placed in the middle of the SelectOneMenu.
Sometimes it works, sometimes it doesn't.
Also if I switch User now, I only get the first letter of it. (Inside the dropdown the full name is written tho)
I populate the content inside a ManagedBean (#ViewScoped) in it's PostConstruct and get the data from database. (View -> ManagedBean -> DAO class -> ManagedBean).
I also tried to put the code inside public Classname{} with the same result.
I think there is a problem with the SelectOneMenu not correctly being rendered.
How to fix that?
users.xhtml:
<p:selectOneMenu id="somSelect" value="#{userManagerBean.somValue}"
styleClass="selecters">
<p:ajax update="userDataTable" listener="#{userManagerBean.changeSomValue}" />
<f:selectItems value="#{userManagerBean.userList}" />
</p:selectOneMenu>
ManagedBean #ViewScoped:
#PostConstruct
public void init() {
// DAO Method
retrieveTableData();
String loggedInUser = "";
try{
loggedInUser = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sprintUser").toString();
}catch(Exception e){
System.err.println("> No previous login");
}
// Check for session login name and select from table - if session null select first
if (somValue == null && userList.size() != 0) {
somValue = userList.get(0);
for(int i = 0; i < userList.size(); i++){
if(loggedInUser.equals(userList.get(i))){
somValue = loggedInUser;
}
}
}
selectedUser = somValue();
userData = new ArrayList<User>();
// a Table population
populateUser(userData);
}

Related

Getting unwanted popup "You have not saved your changes. If you close this flow, then your changes will be lost. Do you want to continue?"

Getting this popup every time whenever calling a bean method via valueChangeListener property from SelectOneChoice in a jsff page.
I need help to block this unwanted popup.
SelectOneChoice's property of the .jsff page:
<af:selectOneChoice value="................."
label=".................."
required="..............."
shortDesc=".............."
id="....................."
valueChangeListener="#{TransferWorkAreaBean.onBookLovChange}"
autoSubmit="true">
<f:selectItems value="............" id="si2"/>
<f:validator binding="......."/>
</af:selectOneChoice>
Method in Bean Class::
public void onBookLovChange(ValueChangeEvent valueChangeEvent) {
valueChangeEvent.getComponent().processUpdates(FacesContext.getCurrentInstance());
invokeELMethod("#{bindings.methodToExecute.execute}", new Class[0], new Object[0]);
AdfFacesContext.getCurrentInstance().addPartialTarget(getBusinessTable());
}
Method details of binding Method::
public void executeInvetoryQueryOnBookChange(String btg) {
OAViewObjectImpl vo = getBusinessOverview();
VariableValueManager vvm = vo.ensureVariableManager();
vvm.setVariableValue("bindBookTypeCode", btg);
vo.executeQuery();
}
Please note, in some places I have used encrypted data for policy.
Please also note, that the uncommittedDataWarning property is not ENABLED.
This popup only appear when the option uncommittedDataWarning is set to "on" at the root af:document tag. Try to run a full search in your JDevelopper for "uncommittedDataWarning".
Another way of avoiding this popup in this specific case would be to ensure that your data are committed or rollback in your data model. As the popup only appear if some data aren't committed when a user navigate outside the af:document. You could run something like so right before your
invokeELMethod("#{bindings.methodToExecute.execute}", new Class[0], new Object[0]);
How to commit if needed (https://cedricleruth.com/how-to-programmatically-commit-or-rollback-a-transaction-in-oracle-adf/)
private void commitIfDirty() {
try {
ViewObject vo = this.getViewObjectFromIterator("YOUR_ITERATOR_NAME");
boolean isNotSaved = vo.getApplicationModule()
.getTransaction()
.isDirty();
if (isNotSaved) {
vo.getApplicationModule()
.getTransaction()
.validate();
vo.getApplicationModule()
.getTransaction()
.commit();
}
} catch (ValidationException validationException) {
//log it and warn the user that his data isn't valid
} catch (Exception error) {
//log it and warn the user something went wrong
}
}
private ViewObjectImpl getViewObjectFromIterator(String nomIterator) {
ViewObjectImpl returnVO = null;
DCBindingContainer dcb = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
if (dcb != null) {
DCIteratorBinding iter = dcb.findIteratorBinding(nomIterator);
if (iter != null) {
returnVO = (ViewObjectImpl)iter.getViewObject();
}
}
return returnVO;
}

How can show when I am logging in for the first time in the storefront - T&C popup in hybris?

How can show when I am logging in for the first time in the storefront - T&C popup in hybris?
For example I am a new customer and I am loggin in store front for the first time, then I will see a popup with some "T&C of use" that I must check to be able to enter the shop.
Maybe I must have some flag whom I say:
private boolean flag = false;
if user is login for first time
flag = false;
if(flag == false){
show me pop up with T&C
flag = true;
}
But how can I get this last login or maybe have another way to do this?
Why not create a boolean flag acceptedTAC on customer type? If someone requests a page on your storefront who has this flag set to null or false, you can show this popup. When the user clicks the accept button, do an AJAX request to your server and set the acceptedTAC flag to true.
This way you even have an "evidence" that a user accepted the TAC. Additionally you can query your database for users who did not yet accept the TAC.
However the usual way you would force the user to accept the TAC would be during registration. A user can only register when he/she accepts the TAC.
Here are the necessary steps:
myextension-items.xml
<itemtype code="Customer" ...>
<attributes>
<attribute name="acceptedTermsAndConditions" type="java.lang.Boolean">
..
</attribute>
<attributes>
</itemtype>
ShowTermsAndConditionsPopupBeforeViewHandler
public class ShowTermsAndConditionsPopupBeforeViewHandler implements BeforeViewHandler {
#Resource
UserService userService;
#Override
public void beforeView(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView) {
UserModel user = userService.getCurrentUser();
if (user instanceof CustomerModel && !userService.isAnonymousUser(user)) {
CustomerModel customer = (CustomerModel) user;
modelAndView.addObject("showTermsAndConditionsPopup", BooleanUtils.isNotTrue(customer.isTermsAndConditionsAccepted()));
} else {
modelAndView.addObject("showTermsAndConditionsPopup", false);
}
}
}
Register BeforeViewHandler in spring-mvc-config.xml
...
<util:list id="defaultBeforeViewHandlersList">
...
<bean class="my.package.ShowTermsAndConditionsPopupBeforeViewHandler"/>
...
</util:list>
...
Create JavaScript Variable in javaScriptVariables.tag
...
ACC.config.showTermsAndConditionsPopup=${showTermsAndConditionsPopup};
...
Add logic to open popup in JavaScript
...
if(ACC.config.showTermsAndConditionsPopup) {
showPopup();
}
...
Create popup content with form:
<c:url var="url" value="/acceptTermsAndConditions" />
<form action="${url}" method="POST">
<label for="acceptTermsAndConditions">I accept Terms and Conditions</label>
<input type="checkbox" id="acceptTermsAndConditions" name="acceptTermsAndConditions" />
<button type="submit>Submit</button>
</form>
Create TermsAndConditionsController
#Controller
public TermsAndConditionsController {
#Resource
private UserService userService;
#Resource
private ModelService modelService;
#RequestMapping(value = "/acceptTermsAndConditions", method = RequestMethod.POST)
#ResponseBody
#ResponseStatus(value = HttpStatus.OK)
public void acceptTermsAndConditions() {
UserModel user = userService.getCurrentUser();
if (user instanceof CustomerModel && !userService.isAnonymousUser(user)) {
CustomerModel customer = (CustomerModel) user;
customer.setAcceptedTermsAndConditions(true);
modelService.save(customer);
}
}
}
If you really want to show T&C popup only once, I would say show it on Registration time.
Let's assume you want to show T&C on each login you can take help of the cookie.
The idea is, after successful login, check for the cookie(let's say "terms"), if not found then show your popup. Now based on user input you can store that cookie.
Just an example.
Source jsfiddle [ http://jsfiddle.net/9q8jmv3L/2/ ]
$(document).ready(function () {
if(${loggedInUser})
{
var visit = getCookie("terms");
if (visit == null) {
x = confirm("Your Message Goes here and you only get to see it once!");
if (x == true)
{
var expire = new Date();
expire = new Date(expire.getTime() + 7776000000);
document.cookie = "terms=here; expires=" + expire;
}
}
}
});
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
Commnent:
If you really want to keep flag then you can have a new attribute in your customer model. Now check that attribute/flag inJavaScript on success login. If the flag is false show the popup. based on the user's action on the popup, update the flag using ajax call

p:autoComplete not firing p:ajax event

I had this issue for a few hours and I surfed the net to try and find the solution but unfortunately I came up short.
Here is what I want to do.
I want to set p:outputText values when item in my autoComplete gets selected.
Here is the code:
<p:autoComplete
completeMethod="#{dynamicSearchBean.getCustomers}"
minQueryLength="1">
<p:ajax event="itemSelect"
listener="#{dynamicSearchBean.handleSelection}"
update="addName"/>
</p:autoComplete>
<h:outputText id="addName" value="#{dynamicSearchBean.firstName}"/>
And the backing bean:
public void handleSelection(SelectEvent event)
{
String value = (String) event.getObject();
System.out.println("selected "+value);
}//end method handleSelection
My autoComplete is working fine by getting values from DB but no event is being triggered when I select the value, and that is the main issue here.
Thanks for the help!
try this
public void handleSelection(SelectEvent event)
{
String value = (String) event.getObject();
this.firstName=value;
}//end method handleSelection

Primefaces TabMenu active tab remembered on logout

As the title explains by itself, I have an issue with managing the currently active tab in the tab menu. I'm using JSF 2.1 w/ PF 3.4. Here is the code fragment with the tab menu:
<h:form>
<p:tabMenu activeIndex="#{navigationMB.activeIndex}" >
<p:menuitem value="Početna" action="#{navigationMB.navigateStudent('home')}" icon="ui-icon-home" />
<p:menuitem value="Konsultacije" action="#{navigationMB.navigateStudent('konsultacije')}" icon="ui-icon-search" />
<p:menuitem value="Zakazivanje" action="#{navigationMB.navigateStudent('zakazivanje')}" icon="ui-icon-document"/>
<p:menuitem value="Profesori" action="#{navigationMB.navigateStudent('profesori')}"/>
<p:menuitem value="Moj profil" action="#{navigationMB.navigateStudent('profil')}" icon="ui-icon-person" />
</p:tabMenu>
</h:form>
Here is the code of the backing bean which serves for the sole purpose of navigating that tab menu:
#Named(value = "navigationMB")
#RequestScoped
public class NavigationMB {
private int activeIndex = 0;
public NavigationMB() {
}
public String navigateStudent(String page) {
System.out.println("go to page " + page);
if ("home".equals(page)) {
activeIndex = 0;
return "/student/home?faces-redirect=true";
}
if ("konsultacije".equals(page)) {
activeIndex = 1;
return "/student/allConsults?faces-redirect=true";
}
if ("zakazivanje".equals(page)) {
activeIndex = 2;
return "/student/newConsult?faces-redirect=true";
}
if ("profesori".equals(page)) {
activeIndex = 3;
return "/student/allProfessors?faces-redirect=true";
}
if ("profil".equals(page)) {
activeIndex = 4;
return "/student/profile?faces-redirect=true";
}
return "";
}
This runs fine when just browsing, but when I logout (invalidate the session) and later return with same or different user, the activeIndex is remembered. Am I not understanding something here? I suppose that the request scoped bean would be created every time there's a navigation action, and even if the user doesn't navigate anywhere, the integer I set to 0 would always point to "home" but it doesn't.
Any help would be awesome.
edit:
It seems that even without logging out, when two users (two tabs in browser) navigate around, if user 1 clicks on, for instance, tab menu item 2, and user 2 refreshes his page, user 2 will see tab menu item 2 selected as well, and vice versa.
edit2: I made a mistake with the previous edit, please forget about this above (I didn't notice that refresh on user 2 side actually loads user 1 with his view).
As discussed among the comments of the question, the bean is not recognized as being request scoped. It is created during application startup and lives as long as the application is running.
As Spring is used, using Spring annotations will resolve this issue:
#Scope("request")
public class NavigationMB {
}
For a request scoped bean, or:
#Scope("session")
public class NavigationMB {
}
to make it session scoped.

a4j:support onchange event not firing

I'm trying to rerender a second dropdown when i change the value in the first one.
But nothing happens when I click and change the value in the first drop down.
Have I missed any crucial part?
My xhtml:
<h:form>
<h:selectOneMenu value="#{adminBean.currentLeadCategory}" required="true" styleClass="formfield fpgeo" style="width:20em;margin-right:20px;">
<a4j:support event="onchange" action="#{adminBean.currentLeadCategoryChanged()}"
reRender="componentToReRender"/>
<s:selectItems value="#{leadCategories}" var="leadCategory" label="#{leadCategory.name}" noSelectionLabel="Choose Category"/>
<s:convertEntity/>
</h:selectOneMenu>
<a4j:outputPanel id="componentToReRenderWrapper">
<h:selectOneMenu id="componentToReRender" value="#{adminBean.currentCounty}"
styleClass="formfield fpgeo" style="width:20em;margin-right:20px;">
<s:selectItems value="#{adminBean.counties}" var="county" label="#{county.name}" noSelectionLabel="choose"/>
<s:convertEntity/>
</h:selectOneMenu>
<h:messages/>
</a4j:outputPanel>
</h:form>
My bean:
#AutoCreate
#Scope(ScopeType.CONVERSATION)
#Name("adminBean")
#MeasureCalls
#Restrict("#{s:hasRole('admin') or s:hasRole('sales')}")
public class AdminBean implements Serializable {
private LeadCategory currentLeadCategory;
private List<County> counties = new ArrayList<County>();
private County currentCounty;
#Factory(value = "leadCategories", autoCreate = true, scope = ScopeType.SESSION)
public List<LeadCategory> fetchLeadCategories() {
Query query = entityManager.createQuery("select l from LeadCategory l");
return query.getResultList();
}
public LeadCategory getCurrentLeadCategory() {
return currentLeadCategory;
}
public void setCurrentLeadCategory(LeadCategory currentLeadCategory) {
this.currentLeadCategory = currentLeadCategory;
}
public County getCurrentCounty() {
return currentCounty;
}
public void setCurrentCounty(County currentCounty) {
this.currentCounty = currentCounty;
}
public void currentLeadCategoryChanged() {
this.loadCountiesForCategory();
}
public List<County> getCounties() {
return counties;
}
public void setCounties(List<County> counties) {
this.counties = counties;
}
public void loadCountiesForCategory(){
if(currentLeadCategory == null){
counties = new ArrayList<County>();
}
counties = new ArrayList<County>(currentLeadCategory.getCounties());
}
}
EDIT 1:
If i check firebug i get an error:
Timestamp: 7/19/12 4:14:44 PM
Error: ReferenceError: A4J is not defined
Source File: http://localhost:8080/admin/admin.seam?cid=11
Line: 1
Ok found the problem! Major crazyness going on here. Someone has set LoadScriptStrategy
param to NONE in the web.xml. This makes that the framework.pack.js and ui.pack.js is NOT loading.
<context-param>
<param-name>org.richfaces.LoadScriptStrategy</param-name>
<param-value>NONE</param-value>
</context-param>
Found this page at docs.jboss
If you use the "NONE" strategy, you must include the following scripts
in your portlet or portal page header. If you are using JBoss Portal,
you can add this to the jboss-portlet.xml file.
Added <a4j:loadScript src="resource:///org/ajax4jsf/framework.pack.js"/>
to my header template and viola everything works like a charm.
I love my job =)
I can see clearly that your xhtml has an ending tag </a4j:outputPanel> but no starting tag: <a4j:outputPanel>
If you rearrange your tags it will work.

Categories

Resources