Sunday, 27 August 2017

Oracle ADF SELECT Statement Query Result


ADFFacesContext adfFacesContext1=AdfFacesContext.getCurrentInstance();
adfFacesContext1.addPartialTarget(text2);


<af:inputText label="Label 1" id="it1" binding="#{test1.text1}"/>
<af:button text="button 1" id="b1" actionListener="#{test1.Copybtn}"/>
<af:inputText label="Label 2" id="it2" binding="#{test1.text2}" partialTriggers="b1"/>


When-Validate-Item:
Text1:[  ]
Text2:[  ]
Need to enter Department number in text1 then automatically populate Text2 value based on Text1.
Steps:
Properties for Text2:
                PartialTrigger: Text1
Properties for Text1:
                AutoSubmit: True

Resetting form in ADF popup / Reset Any component

While developing a Form on ADF pop-up I have learned that the pop-up is fetched once on page load. On canceling the pop-up & open it again it still persists its data which is not what we all need.
I have tried many ways to reset the form as setting contentDelivery=”lazyUncashed” , resetting all the fields programmatically , delete dirty data & clear VO cache associated with the form. Until i found the magic line which resets the component as it wasn’t fetched before
UIComponent myPopupComponent = actionEvent.getComponent();
oracle.adf.view.rich.util.ResetUtils.reset(myPopupComponent);





Resetting the page contents or undoing the changes made by a user is a very common use case scenario in Rich Internet Applications. The 'reset action' should skip all validations defined on the current page and page contents needs to restored from the underlying data layer. Some of the web frameworks support this feature out of the box. Let me try explaining possible ways to reset a page when developing applications using ADFFaces. 

1. <af:resetButton>

As the name suggests, af:resetButton resets the contents of a form. Please note that developer doesn't have much control here as he/she might not be able to bind any action method with this built in reset button.

<af:resetButton  text="ResetButton" id="rb1"/>
2. <af:resetActionListener>

This tag is usually bound to an action source like command button to reset all submitted values whenever an action is triggered. Obviously this gives more control to the developer as the action sources like command button can be optionally bound to an action method through the Expression Language(EL). Please note that, you may need to keep immediate="true" for the command button ( for the action source ) to skip the validations while implementing the reset/cancel behavior. 

 
<af:commandButton text="Cancel with resetAction" id="cb2"  immediate="true"  
     partialSubmit="true"
     actionListener="#{SomeBean.cancelBusinessAction}">
     <af:resetActionListener/>
</af:commandButton>

Why do we need to reset submitted values? 

Each component has local cache value. When you submit a form, submitted value gets assigned to this localValue at the end of 'PROCESS VALIDATIONS' pahse, and thereafter submitted value is set as null. During the RENDER RESPONSE, first consult the local value property of this component. If non-null return it. If null, see if we have a ValueExpression for the value property. UIInput::resetValue() reset the submitted value that would force the rendering logic to take the value from the model/binding layer. 

3. Custom Reset Implementation 

So far so good, but in some scenarios developers may need to dirty their hands a bit to get the job done - where the declarative 'reset' support is missing. I noticed a rare use case scenario recently, that calls for custom reset implementation. There master-detail data is displayed in tabular form and user is allowed to edit one master record (and it's children as well) at a time, then save that record and proceed to next. In case user decided to navigate to next record without saving current record, then current changes needs to be cancelled. Though use case is bit odd one, adding this feature is pretty simple. All we need to is override the default selectionListener and from this custom method, parse the component tree and call reset on each element. 
Code Snippet:

  
 public void customSelectionHandler(SelectionEvent selectionEvent) {

     UIComponent source = (UIComponent)selectionEvent.getSource();
     UIComponent uiComp = _getRootToReset(source);
     _resetChildren(uiComp);
     EL.invokeMethod(
     "#{bindings.DepartmentsView11.collectionModel.makeCurrent}",
     SelectionEvent.class, selectionEvent);
}
  

On a related note, I would suggest you to look at the source of org.apache.myfaces.trinidadinternal.taglib.listener.ResetActionListener, that may help you to understand the 'reset' concept much better. (Even the below given sample application just tries to reuse the same reset logic from ResetActionListener class). 





package de.hahn.blog.resetformfields.view.backing;

import javax.faces.component.UIComponent;
import javax.faces.event.ActionEvent;
import oracle.adf.share.logging.ADFLogger;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;
import oracle.adf.view.rich.component.rich.nav.RichResetButton;
import oracle.adf.view.rich.util.ResetUtils;


public class BRFFBean
{
    private static ADFLogger _logger = ADFLogger.createADFLogger(BRFFBean.class);
    private RichCommandButton buttonResetActionListener;
    private RichCommandButton buttonResetByBean;
    private RichResetButton buttonResetButton;

    public BRFFBean()
    {
    }

    public void resetFormFieldsListener(ActionEvent actionEvent)
    {
        // check if hte action has a component attatched
        UIComponent uiComp = actionEvent.getComponent();
      
        if (uiComp == null)
        {
            // if not we use the button which we bound to this bean
            uiComp=getButtonResetByBean();
            _logger.info("reset fields: buttonID = " + uiComp.getId());
        }
        else
        {
            _logger.info("reset fields: CompID = " + uiComp.getId());
        }
        // pass component inside the UIForm, UIXForm, UIXSubform, UIXRegion, UIXPopup, RichCarousel
        // or RichPanelCollection which holds the components to reset
        ResetUtils.reset(uiComp);
    }

    public void setButtonResetActionListener(RichCommandButton buttonResetActionListener)
    {
        this.buttonResetActionListener = buttonResetActionListener;
    }

    public RichCommandButton getButtonResetActionListener()
    {
        return buttonResetActionListener;
    }

    public void setButtonResetByBean(RichCommandButton buttonResetByBean)
    {
        this.buttonResetByBean = buttonResetByBean;
    }

    public RichCommandButton getButtonResetByBean()
    {
        return buttonResetByBean;
    }

    public void queueAction1Listener(ActionEvent aEvent)
    {
        _logger.info("Queue action for button wiht af:resetActionListener");
           
        ActionEvent actionEvent = new ActionEvent(this.getButtonResetActionListener());
        actionEvent.queue();
    }

    public void queueAction2Listener(ActionEvent aEvent)
    {
        _logger.info("Queue action for af:resetButton");
        ActionEvent actionEvent = new ActionEvent(this.getButtonResetButton());
        actionEvent.queue();       
    }

    public void setButtonResetButton(RichResetButton buttonResetButton)
    {
        this.buttonResetButton = buttonResetButton;
    }

    public RichResetButton getButtonResetButton()
    {
        return buttonResetButton;
    }
}






To set first value as default value in Select One Choice in adf table

Sometimes we need to set first value as default value in Select one choice. For that , we may have so many options :
We can give unSelectLabel property of SelectOneChoice component. But we could not get that value in backing bean. (we can display in UI only but its value is null).
<af:selectOneChoice value=”#{bindings.DepartmentId.inputValue}”
unselectedLabel=”Select Value” …./>
But we don’t want null and it to be some proper value like 1st value in the drop down.
Another option to set that in managed bean , create binding to that drop down in managed bean and in its setter we can add the following code :
public void setChoice(RichSelectChoice choice) {
this.choice = choice;
this.choice.setValue(0);  // here we can set 1st value (with index o as default value to the drop down)
}
we can display it in the ui properly while loading the page, but when we scroll up and down in the table with that drop down in a column, it can’t set the default value to that component. It will result in blank.
In such scenario’s we have another option to achieve this :
To create LOV , I have added some view object as view accessor to the main vo and created transient attribute. To that attr I have added LOV.
Now create RowImpl class for the VO and in the getter method of transient attribute add the following code :
public String getReopen() {
if(getAttributeInternal(REOPEN)!=null)
return (String) getAttributeInternal(REOPEN);
else
{
Row row = (Row)this.getLookupVA().first();  // first row from view accessor
if(row!=null)
return (String)row.getAttribute(“LookupCode”);
}
return null;
}
It will automatically return the first value from drop down as the default value.






How To in Jdeveloper ADF Tutorials- reset the inputText component values

Sometimes the value of the inputText component is not refreshed and the value that was previously entered will still persist within the component. To overcome this issue. we have to use the resetValue() method to reset the component value and display the components intial state
What it does:
Get handle to the inputText component using the JSFUtils find component method with the inputText id passed as a parameter
set the submitted value of the inputText as null
reset’s the input component value
refresh the component

private void resetInputText(String id) {
RichInputText input = (RichInputText)JSFUtils.findComponentInRoot(id);
input.setSubmittedValue(null);
input.resetValue();
AdfFacesContext.getCurrentInstance().addPartialTarget(input);
}
Usage:
This method is used to reset the inputText component value’s in a popup, af:formlayout, af:table.



ADF UI - Resetting or Clearing form fields in ADF popup on clicking ' Cancel '.
Sample UseCase: Suppose the popup has input form fields to enter data with say OK and Cancel buttons, and when the user enters data and clicks on 'Cancel' button, we need to close the popup and reset all values entered in the popup's fields. If you don't reset the values, if you invoke the same popup again, it'll show the same previously entered values in the form which is unwanted. So, how to show the popup without the previous values?

Solution:
1. Set popup's 'contentDelivery' property to 'lazyUncached'. Setting this property won't cache the data entered and won't restore the previously entered values. This is highly recommended to set contentDelivery="lazyUncached" for better performance as the popup will be loaded only on invocation but not at the time of page loading.


2. If the step1 doesn't work, drop af:resetActionListener as a sub-element to 'Cancel' button in the popup. ResetActionListener will reset the form fields in the popup. We can also call ResetActionListener programmatically in an actionlistener method as follows using Oracle's internal API.


But, using internal API in the code is not encouraged. There is public API to achieve the same using the below code.


But, this Public API is not yet available in the latest publicly available Jdeveloper available and it'll be available in the upcoming versions. Until then, we need to go ahead using internal API only as shown in step2.
You might also like:





How to Identify a View Object is modified
Create Action Listener for the Next button and name the bean as ModifiedVOBean.java and method as chkmeth. Inside the method get the bindings for the EmployessVO1 .

        DCBindingContainer bindings2 =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
              
        JUCtrlHierBinding obj = (JUCtrlHierBinding)bindings2.findCtrlBinding("EmployeesVO1");
        ViewObject targetVO = obj.getViewObject();

we can get the current status of the view object instance using a method isDirty().

Boolean b = targetVO.getApplicationModule().getTransaction().isDirty();

This gives Boolean value of True/False . If something is modified/created the value will be True else False.



Final piece of code is 

    public void chkMeth(ActionEvent actionEvent) {
       
        DCBindingContainer bindings2 =
            (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
              
        JUCtrlHierBinding obj = (JUCtrlHierBinding)bindings2.findCtrlBinding("EmployeesVO1");
        ViewObject targetVO = obj.getViewObject();
        Boolean b = targetVO.getApplicationModule().getTransaction().isDirty();
       FacesMessage msg=null;
        Boolean ev = false;
        if(b!=ev){
        msg=new FacesMessage("Hold on ,you have unsaved data.pls commit before proceeding");
        FacesContext.getCurrentInstance().addMessage(null,msg);
        }

  }

The boolean result  can be evulated against True/False and based on it we can throw a message to the user . Now go to the page and change something in any of the column and click Next. you will get the message.Further  you can customize the implementation the way u want like information in the pop up dialog
and so on.




we can also able to get Entity level status from VO using this code

RowSetIterator rs1 =targetVO.createRowSetIterator(null);
while (rs1.hasNext()) {
  EmployeesVORowImpl r = rs1.next();
  Entity eo = r.getEntity(0);
byte currentState= eo.getEntityState();
if(currentState==EntityImpl.STATUS_NEW .......)
{
 ......
}
}

From design time we can access the row status using the following expression
Expression #{row.row.entities[0].entityState}

Getting the View object in MB and performing operations on it is not a good practice.







ADF : Accessing column value from ADF table row

There are cases where we need to show only a number in the Ui that comes from a different ViewObject .. Infact the real case scenario is ViewObject that has count(*) as result and we need to print that to the user in a tab or textbox.. look at the example


The Tab displays the Total Countries ..

select countries(*) as Count from COUNTRY group by countries ; This will return a single value..we generally tend to use VO.getEstimatedRowCount to get all the rowvalues and display .. The way to achieve and retrieve this is very simple ...


Following code snippet will help to achieve that

 public int getCount() {

        Long val = 0;
        ViewObject vo = this.getCountryVO();
        vo.executeQuery();
        RowSetIterator rsIterator = vo.createRowSetIterator(null);
        rsIterator.reset();
     
       while (rsIterator.hasNext()) {
            Row row = rsIterator.next();
            val = ((BigDecimal)row.getAttribute("Count1")).longValue();
        }

        rsIterator.closeRowSetIterator();
        return val;

  }

Expose this method in the AM Client Interface .Add this method  to the page bindings as methodAction. Go to executable section in the pagedef , add invokeAction to this method . This will get invoked every time when the page is loaded . This brings the count available during pageload

Add this expr to the place where you need to print the result .
#{bindings.getCount.resul}

You can also access that method directly on clicking some button or link via ActionListener without having to InvokeAction under executables section ...


=================
     
 <b>in Jsff :</b>

 <af:inputText label="Id" id="it1" binding="#{pageFlowScope.SourceFile1.id}"/>
        
 <b>in Bean</b>
       
  private RichInputText id;

 public void setId(RichInputText id) {
this.id = id;
 }

 public RichInputText getId() {
 return id;
  }
       
  public void onClickSubmit(ActionEvent actionEvent) {
  System.out.println(this.getId().getValue().toString());
  }


=====================

ADF DataControl Built-in View Operations - Part II
Followed from ADF Data Control built-in view operations I .

1) Execute :

      It will execute the View Object's Query . It Refreshes the data collection . This is similar to
      vo.executeQuery();

2) ExecuteWithParameters :

     This operation appears only for ADF view objects that have defined one or more bind variables . This  will also execute the view object with the parameter values being passed to the bind variables .


3) setCurrentRowWithKey :

    If ever want to avoid the default selected row of view object and set an any other row as current row , you can do this using setCurrentRowWithKey . Every row in the view object will have a String representation that uniquely identifies a particular row and using that string being passed as a parameter to rowset. If found set that as current row .

Note :  This Method will work only on the collection that has only one key attribute.

3) setCurrentRowWithKeyValue :

          This takes the value for a key attribute , if found set that as current row.

you can access the value of the string key of  a row  by using  rowKeyStr property  (e g:#{row.rowKeyStr})

4) removeRowWithKey :

      If ever want to delete a particular row you can remove that row using removeRowWithKey. The delete operation can be used to delete rows but it will always delete the current row.
   









Hi All,
When ever we want to have value of some attribute we can use below code .It work fine in managed and backing bean .
Create a java class and import
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCBindingContainer;

import oracle.adf.model.binding.DCIteratorBinding;
and using below code get value of any attribute
BindingContext ctx = BindingContext.getCurrent();
DCBindingContainer bc = (DCBindingContainer)ctx.getCurrentBindingsEntry();
DCIteratorBinding iterator = bc.findIteratorBinding("ViewObjectIterator");
Row r = iterator.getCurrentRow();
String empNameValue = (String)r.getAttribute("EmpName");





No comments:

Post a Comment