Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label Programmatically. Show all posts
Showing posts with label Programmatically. Show all posts

Wednesday 3 August 2016

ADF Basics: Iterate over master detail viewObject using view link accessor


Hello All

This post is about iterating over master and it's child view object using view link accessor, this is very basic thing of framework still some find (those who are starting with ADF) it difficult so I thought to write it here

Here I am using Departments and Employees table of HR Schema to create Master-Detail relation and due to view link relation, Department viewObject has view link accessor of Employees viewObject

Saturday 30 July 2016

ADF Basics: Populate simple programmatic View Object using POJO


Hello All

I hope you all know that we have 4 type of viewObjects in ADF, Here we'll discuss about a simple programmatic viewObject
  • Entity Object Based
  • SQL Query Based
  • Static List Based
  • Programmatic ViewObject
Programmatic ViewObject can be created by overriding appropriate methods in ViewObject's Impl class to retireve data from REF CURSOR, Array or any Java file
Here in this post I am using an ArrayList (POJO based) to populate viewObject records so for that I'll override some methods of ViewObject Impl class

Saturday 18 June 2016

Add and delete records (Parent/Child) in POJO Based ADF TreeTable


Hello All

Previously I have posted about creating POJO based ADF TreeTable , Get Selected Record from POJO based TreeTable and Traverse POJO based TreeTable

Recently a developer asked me about adding and deleting records in POJO based TreeTable so here goes a new blog post

To add records in af:treeTable first we have to check that if user has selected any parent node then new record will be added under it and if there is no selection then new record will be added as parent node, This is the core concept of this post and all these posts uses same sample application and same 2-Level Tree


Tuesday 7 June 2016

Open af:inputListOfValues popup by calling JavaScript programmatically


af:inputListOfValues provides option to open Lov values in a popup and allow user to search, We can open this popup by clicking on magnifying glass icon


Recently I have seen a thread on OTN forum where user wants to open lov popup on a button click after checking some conditions and also found a post by Frank Nimphius Where he used javascript to open Lov popup on double click of mouse.
So guess what I have done ? ;)
Just called that javascript fucntion programmatically on button click

Thursday 19 May 2016

Traverse POJO based ADF treeTable, Get Child nodes of selected parent


Previosuly I have posted about populating af:treeTable programmatically and getting selected records from POJO based treeTable

This post is next in that series and here I am extending same sample application that show a tree of Seasons and it's characters
First we will see How to traverse a POJO based treeTable (Iterate through all nodes of treeTable)

Basic idea is to get treeTable Collection Model and iterate over it to get all nodes value, To get CollectionModel created treeTable component binding in managed bean

Monday 16 May 2016

How to queue SelectionEvent programmatically, Call af:table Selection Listener programmatically

Hello All
Hope you all are doing good :) 
Previously I have posted about defining custom selection listener for af:table and perform desired operation on selection event of table row

Selection Listener is fired when server receives a selection event from client means whenever user selects a row in table (Selection Event) then server process that event and execute selection listener defined in managed bean

And this post is about creating selection event programmatically without user interaction with table.
In ADF we can queue ActionEvent , ValueChangeEvent and in same manner we can create and queue SelectionEvent programmatically

Friday 13 May 2016

Get Selected records (Child/Parent) from POJO based ADF treeTable

Hello All
Previously I have posted about creating af:treeTable programmatically using POJO and this the next post in series

In this post I am talking about a very common requirement while using POJO based treeTable
How can we get selected records (child/parent) from POJO based treeTable ?

For this post I am extending same sample application, Till now we have seen that how can we create POJO based treeTable
Now we'll see that how to get it's selected records


Saturday 30 April 2016

Create ADF Choice List and apply selectItems to it programmatically

I hope we all know how to create selectOneChoice using Model layer and previously I have posted about populating selectOneChoice programmatically from bean using ArrayList

Programmatically populate values in a af:selectOneChoice component in ADF

But this post is slight different - It is about creating selectOneChoice component and applying selectItems to it programmatically
There is nothing complicated in this , Just a piece of code is required
Here I have used an ArrayList to set SelectItems and created component binding for af:form to add selectOneChoice as it's child 

Thursday 21 April 2016

ADF Basics: Get display and base value of POJO based SelectOneChoice


Previously I have posted about populating selectOneChoice programmatically using POJO

and this post is about getting selected value of POJO base selectOneChoice (both display value and base value)

Thursday 21 January 2016

Add and delete values in POJO based selectOneListbox/selectOneChoice in ADF

Previously i have posted about populating selectOneChoice programmatically using POJO
Programmatically populate values in a af:selectOneChoice component in ADF

In same way we can populate values in selectOneListBox as both ADF Faces components are used for single selection and share same structure

Saturday 5 September 2015

Apply ValueChangeListener to programmatically created ADF Faces components

Again a post in series of  Working with ADF Faces Components programmatically
Previously i have posted about Getting value , Applying Action Listener , Applying Client/Server Listener, Creating and applying client Attributes, Setting value expression , Applying Validation to programmatically created component
Now this post post is about applying Value Change Listener to a component that is created at run time
See how to do this (Jdev 12.1.3)-
  • First created a FusionWebApplication and a page in viewController project
  • Dropped a button on page , on this button action i will create an inputText programmatically and assign Value Change Listener method reference to it
  • To create new inputText i have added following code (described in previous post)

Tuesday 1 September 2015

Apply Validator to programmatically created ADF Faces components

Again a post in series of  Working with ADF Faces Components programmatically
Previously i have posted about Getting value , Applying Action Listener , Applying Client/Server Listener, Creating and applying client Attributes, Setting value expression  to programmatically created component
Now this post post is about applying Validator to a component that is created at run time
See how to do this (Jdev 12.1.3)-
  • First created a FusionWebApplication and a page in viewController project
  • Dropped a button on page , on this button action i will create an inputText programmatically and assign validator method reference to it
  • To create new inputText i have added following code (described in previous post)

Thursday 20 August 2015

Set EL expression in value (properties) of programmatically created ADF Faces component


When we are working with ADF Faces components programmatically then we  create , set styles,set value of that component from managed bean
This post is about setting an expression as component value that will be resolved at run time and return desired value

Monday 17 August 2015

Showing HashMap values in af:table using af:iterator

Previously i have posted about populating af:table programmatically using List Data Structure
Populate af:table programmatically from managead bean using POJO

This post covers same topic but this time requirement is different , we have a HashMap in managed bean and requirement is to show it's values on page in a table view
See Managed Bean code-


    //HashMap and it's accessors
    private HashMap<String, String> valMap = new HashMap<String, String>();

    public void setValMap(HashMap valMap) {
        this.valMap = valMap;
    }

    public HashMap getValMap() {
        return valMap;
    }
    // Object array to store key values of HashMap
    public Object[] getKeySet() {
        return getValMap().keySet().toArray();
    }


Added two inputText on page and a button to add new key and value to HashMap,




<af:panelFormLayout id="pfl1">
                    <af:inputText label="Key" id="it1" contentStyle="width:100px;"
                                  binding="#{viewScope.ShowHashMapAsTable.keyTextBind}"/>
                    <af:inputText label="Value" id="it2" contentStyle="width:100px;"
                                  binding="#{viewScope.ShowHashMapAsTable.valueTextBind}"/>
                    <af:button text="Add" id="b1" actionListener="#{viewScope.ShowHashMapAsTable.addValuesToMap}"/>
                </af:panelFormLayout>


Now code on button that get value of both inputText using component binding and add it to HashMap, at run time this form will be used to add new values to HashMap and table


    //Component Binding of inputText to get values
    private RichInputText keyTextBind;
    private RichInputText valueTextBind;

    public void setKeyTextBind(RichInputText keyTextBind) {
        this.keyTextBind = keyTextBind;
    }

    public RichInputText getKeyTextBind() {
        return keyTextBind;
    }

    public void setValueTextBind(RichInputText valueTextBind) {
        this.valueTextBind = valueTextBind;
    }

    public RichInputText getValueTextBind() {
        return valueTextBind;
    }

    /**Add new value to HashMap
     * @param actionEvent
     */
    public void addValuesToMap(ActionEvent actionEvent) {
        if (keyTextBind.getValue() != null && valueTextBind.getValue() != null) {
            valMap.put(keyTextBind.getValue().toString(), valueTextBind.getValue().toString());

        }
    }


Now Bean Part is done , see how to configure af:table to show HashMap values, table is mapped to array of keySet and an iterator is used inside table that derives value using key attribute -
#{cVal[row]}


<af:table var="row" rowBandingInterval="0" id="t1" value="#{viewScope.ShowHashMapAsTable.keySet}"
                              partialTriggers="::b1">
                        <af:iterator id="i1" value="#{viewScope.ShowHashMapAsTable.valMap}" var="cVal">
                            <af:column sortable="false" headerText="Key" id="c2">
                                <af:outputText value="#{row}" id="ot4" inlineStyle="font-weight:bold;color:darkblue;"/>
                            </af:column>
                            <af:column sortable="false" headerText="Value" id="c1">
                                <af:outputText value="#{cVal[row]}" id="ot3"/>
                            </af:column>
                        </af:iterator>
                    </af:table>


Now all done , run and check the application
 Add New Value (1)
  Add New Value (2)

Sample Application- Download (Jdev 12.1.3)
Cheers :) Happy Learning

Saturday 1 August 2015

ADF Baiscs: Define and remove named bind variable in viewObject at runtime programmatically

This post is about creating named bind variable in viewObject at run time and filter viewObject using this bind variable in WHERE Clause of ViewObject programmatically .

Defining WHERE Clause and Bind Variable name and default value -

        //Get ViewObject
        ViewObject vo = iter.getDepartments();

        //Apply desired WHERE Clause and declare bind variable name
        vo.setWhereClause("DEPARTMENT_NAME=:BindDepartmentName");

        //Define this variable as ViewObject Bind Variable , You can also set default value for this
        vo.defineNamedWhereClauseParam("BindDepartmentName", "Purchase", null);

        // Execute ViewObject to finally apply where clause
        vo.executeQuery();




Setting value of Bind Variable-


        //Setting Value of Bind Variable
        vo.setNamedWhereClauseParam("BindDepartmentName", "Finance");
        vo.executeQuery();


Getting value of Bind Variable-


        //Get value of Bind Variable
        vo.getNamedWhereClauseParam("BindDepartmentName");


Removing WHERE Clause and Bind Variable after use-


        //Remove where clause
        vo.setWhereClause(null);
        //Remove Bind Variable
        vo.removeNamedWhereClauseParam("BindDepartmentName");
        vo.executeQuery();

Cheers :) Happy Learning

Friday 17 July 2015

Apply sorting to POJO based af:table programmatically , Using custom sort listener in ADF

Again a post about POJO based table , previously i have posted about-

1.Populating and adding records in POJO based table
Populate af:table programmatically from managead bean using POJO
2. Gettting selected rows from POJO based table
Get selected row (single/multiple) from POJO based table in ADF

This post is about applying sorting to POJO based table , when we drop a viewObject as af:table on page then framework provides sorting and filtering features declaratively, but when populating table from managed bean using List(POJO) then it is not there so we have to do it manually

To understand this post completely , go through previous posts and check attached application there
I have used a PersonBean java bean class to contain columns of table or you can say there is a List of PersonBean type that populates data in af:table. (This is the basic information about application)




Now what to do , see step by step implementation-
  • Select table on page editor and create a sortListener in managed bean to handle sortEvent


  • Now what we have do in sort listener ?
    1.Get active sort criteria using sortEvent
    2.Remove that sort criteria
    3.Sort List Data Structure that is used to populate af:table
    4.Apply sort criteria again on af:table

    See code written in managed bean-

  •     //List to store sort criteria
        private List<SortCriterion> sortedTableList = new ArrayList<SortCriterion>();
    
        public void setSortedTableList(List<SortCriterion> sortedTableList) {
            this.sortedTableList = sortedTableList;
        }
    
        public List<SortCriterion> getSortedTableList() {
            return sortedTableList;
        }
    
        /**Custom Sort Listener for POJO based af:table
         * @param sortEvent
         */
        public void tableSortListener(SortEvent sortEvent) {
            //Get active sortCriteria on table
            List<SortCriterion> activeSortCriteria = sortEvent.getSortCriteria();
            SortCriterion sc = activeSortCriteria.get(0);
            // Remove active criteria from table
            this.removeSortCriteria(sc);
            //Sort List that populates table using Comparator interface
            applySortAsPerColumn(sc.getProperty());
    
            // Add the current criteria to the list
            this.sortedTableList.add(0, sc);
            // Apply sort criteria to table
            RichTable richTable = (RichTable) sortEvent.getComponent();
            richTable.setSortCriteria(sortedTableList);
    
        }
    
        /**Removes sort criteria*/
        private boolean removeSortCriteria(SortCriterion sortCriterion) {
            //Checks that if any sortCirteria is present in list , if yes then remove it
            if (sortedTableList != null && sortedTableList.size() > 0) {
                for (SortCriterion sc : sortedTableList) {
                    if (sc.getProperty().equals(sc.getProperty())) {
                        sortedTableList.remove(sc);
                        return true;
                    }
                }
            }
            return false;
        }
    

    Now logic to apply programmatic sort starts from here , we have to sort List using Java Comparator interface
    To Read more - How to sort ArrayList using Comparator?     Comparator interface

        private void applySortAsPerColumn(String criteria) {
            //Get List that populates table
            List<PersonBean> list = getPersonList();
            //Check which column's sorting is triggered from UI
            //and then sort list on basis of that attribute
            //Sorting of collection makes use of Comparator interface, Read about it
            if ("name".equalsIgnoreCase(criteria)) {
                Collections.sort(list, new ProgTableBean.PersName());
            } else if ("mobNo".equalsIgnoreCase(criteria)) {
                Collections.sort(list, new ProgTableBean.MobNo());
            } else if ("salary".equalsIgnoreCase(criteria)) {
                Collections.sort(list, new ProgTableBean.Salary());
            }
        }
        // Comparator for all attributes to sort List according to different attributes
    
        public static class PersName implements Comparator<PersonBean> {
            private int flag = 1;
    
            @Override
            public int compare(PersonBean o1, PersonBean o2) {
                return flag * o1.getName().compareTo(o2.getName());
            }
        }
    
    
        public static class MobNo implements Comparator<PersonBean> {
            private int flag = 1;
    
            @Override
            public int compare(PersonBean o1, PersonBean o2) {
                System.out.println("In 2**");
                return flag * o1.getMobNo().compareTo(o2.getMobNo());
    
            }
        }
    
    
        public static class Salary implements Comparator<PersonBean> {
            private int flag = 1;
    
            @Override
            public int compare(PersonBean o1, PersonBean o2) {
                return flag * o1.getSalary().compareTo(o2.getSalary());
            }
        }
    


  • Now on page ,select table and set sortable true for each column and set sortProperty same as column name
    Check af:table source after setting all properties

  • <af:table var="row" rowBandingInterval="1" id="t1" value="#{viewScope.ProgTableBean.personList}"
                              partialTriggers="::b1" rowSelection="multiple" binding="#{viewScope.ProgTableBean.tableBind}"
                              selectionListener="#{viewScope.ProgTableBean.tableSelection}"
                              sortListener="#{viewScope.ProgTableBean.tableSortListener}">
                        <af:column sortable="true" headerText="Name" id="c1" width="150" sortProperty="name">
                            <af:outputText value="#{row.name}" id="ot1"/>
                        </af:column>
                        <af:column sortable="true" headerText="Mobile Number" id="c2" sortProperty="mobNo">
                            <af:outputText value="#{row.mobNo}" id="ot2"/>
                        </af:column>
                        <af:column sortable="true" headerText="Salary" id="c3" align="right" sortProperty="salary">
                            <af:outputText value="#{row.salary}" id="ot3"/>
                        </af:column>
                    </af:table>
    

  • All done :) , Run and check application


Sample ADF Application -Download
Cheers :) Happy Learning

Friday 5 June 2015

Programmatically Select all values in ADF BC based selectMany (af:selectManyCheckbox, af:selectManyChoice, af:selectManyListbox, af:selectManyShuttle) component


Hello All,
Previously i have posted a lot about component that supports multiple selection in ADF Faces (af:selectManyCheckbox, af:selectManyChoice, af:selectManyListbox, af:selectManyShuttle)
- Multiple Selection in ADF Faces

This post is about selecting all values in a component programmatically on a event like button click, value change event etc.
Note that this post is designed for ADF BC (viewObject) based components , to set values in bean based component check this-
Programmatically populate values in ADF Faces multiSelect component (af:selectManyCheckbox, af:selectManyChoice, af:selectManyListbox, af:selectManyShuttle)



So for this i have just dropped Departments viewObject as multiSelect component on page
(af:selectManyCheckbox, af:selectManyChoice, af:selectManyListbox, af:selectManyShuttle)


 Page bindings section looks like this-


Now see code of Set all values as selected button-


    /**Method to get BindingContainer of current viewPort (page)
     * @return
     */
    public BindingContainer getBindings() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }



    /**Method to set all values as selected in SelectMany Components.
     * @param actionEvent
     */
    public void setAllValuesToSelected(ActionEvent actionEvent) {

        int arrIndex[];
        //Get the iterator binding of component
        DCIteratorBinding deptIter = (DCIteratorBinding) getBindings().get("DepartmentsView1Iterator");
        //Get viewObject from Iterator
        ViewObject deptVo = deptIter.getViewObject();
        //Get component list binding , component is directly based on this
        JUCtrlListBinding list = (JUCtrlListBinding) getBindings().get("DepartmentsView1");
        DCIteratorBinding iterList = list.getDCIteratorBinding();
        RowSetIterator rsi = deptVo.createRowSetIterator(null);
        int i = 0;
        int rowCount = (int) deptVo.getEstimatedRowCount();
        //Initialize array and set it's size (equal to number of rows in List)
        arrIndex = new int[rowCount];
        while (rsi.hasNext()) {
            //Get viewObject next row from RowSetIterator
            Row nextRow = rsi.next();
            //Set this row as page iterator's current row
            iterList.setCurrentRowWithKey(nextRow.getKey().toStringFormat(true));
            //Now get index of this row
            int indx = iterList.getCurrentRowIndexInRange();
            //Add it to array
            arrIndex[i] = indx;
            i++;
        }
        rsi.closeRowSetIterator();
        // Set as selected indices
        list.setSelectedIndices(arrIndex);
    }


All done, now run and check application , click on button and see what happens ?


Great, it's working :)
I have explained one more approach to set values in multi select component that makes use of component binding
check it - Set values in af:selectManyChoice programmatically - Oracle ADF

Sample ADF Application-Download
Cheers :) Happy Learning

Thursday 4 June 2015

Create and set clientAttribute to ADF Faces component programmatically to pass value on client side JavaScript


This post is next in series of "Working with ADF Faces Components programmatically"

So this post is about creating client Attribute, applying it to component and setting it's value programmatically
this requirement comes in picture when user is dealing with dynamic layout means components are created programmatically at run time and it is not possible to apply clientAttribute and other properties declarative

In this i am extending my previous post -
Apply Client/Server listener to programmatically created components, apply JavaScript to ADF Faces components at run time

In previous post i have described about applying client listener and server listener programmatically
here we will see how to pass a variable value to java script function using client attribute
You can read more about af:clientAttribute here

From oracle docs-
The clientAttribute tag specifies the name/value for an attribute which will both be made available both on the server-side (Faces) component as well on on the client-side equivalent. This tag will be ignored for any server-rendered components, as it is only supported for the rich client. ClientAttributes are not synchronized to the server since unknown attributes from the client are not synchronized to the server.



Lets' see how we can do this ,It's simple just check this code -

//Code from previous post to create inputText programmatically 
//http://www.awasthiashish.com/2015/05/apply-clientserver-listener-to.html
        RichInputText ui = new RichInputText();
        ui.setValue("Programmatically Created Input Text");
        ui.setId("pit1");
        ui.setContentStyle("width:200px;color:navy");

Here i am not writing code to apply client/server listener again , refer previous post for that
See the code to add client attributes to component (inputText)

        // A Set that contains all clientAttributes
        java.util.Set<String> clientAttributes = new HashSet<String>();

        // Add client attribute's name
        clientAttributes.add("clientAttribute1");
        clientAttributes.add("clientAttribute2");
        clientAttributes.add("clientAttribute3");

        //Add these attributes to a UI Compoenent
        ui.setClientAttributes(clientAttributes);

        //here assign values to client attributes
        ui.getAttributes().put("clientAttribute1", "Oracle ADF");
        ui.getAttributes().put("clientAttribute2", 9999);
        ui.getAttributes().put("clientAttribute3", "Ashish Awasthi");

So all done , now check it
For that i have used this javascript method

function demoJsFunction(evt) {
                  var comp = evt.getSource();
                  alert(comp.getProperty('clientAttribute1'));
                  alert(comp.getProperty('clientAttribute2'));
                  alert(comp.getProperty('clientAttribute3'));
               
                  evt.cancel();
              }
 

this method is called using client listener on input text and see the alert messages
First client attribute value-

Second client attribute value-

Third client attribute value-

So this is working :)
Cheers :) Happy Learning

Friday 29 May 2015

Apply Client/Server listener to programmatically created components, apply JavaScript to ADF Faces components at run time

Hello All

This post is next in series of "Working with ADF Faces Components programmatically"
Previous posts are-

Creating dynamic layout (form and UI Component) using ADF Faces
Get Value from programmatically created components , Iterate over parent component to get child values in ADF Faces 
Apply ActionListener to programmatically created buttons/link in ADF

Now this post is about applying client listener & server listener (to execute some javascript function) to a programmatically created component (inputText, outputText etc)

Let's see the implementation part (Jdev 12.13) -

  • First created a FusionWebApplication and a page in viewController project
  • Dropped a button on page , on this button action i will create an inputText programmatically
  • To create new inputText i have added following code (described in previous posts)



  •     /**Method to add dynamically created component to a parent layout
         * @param parentUIComponent
         * @param childUIComponent
         */
        public void addComponent(UIComponent parentUIComponent, UIComponent childUIComponent) {
            parentUIComponent.getChildren().add(childUIComponent);
            AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);
        }
    


            //Code to create af:inputText and add it to panelgroup layout
            RichInputText ui = new RichInputText();
            ui.setValue("Programmatically Created Input Text");
            ui.setId("pit1");
            ui.setContentStyle("width:200px;color:navy");
            //getParentGroupLayoutBind is the component binding of parent panel group layout
            addComponent(getParentGroupLayoutBind(), ui);
    

  • Now first part is done - Creation of input text , next is to assign client and server listener to it
    So for that first we have to add some JavaScript function in page that will be called using clientListener
    I have added this JavaScript function in page, it just fires a custom event from client and pass component value as parameter

  •         function demoJsFunction(evt){
              var comp = evt.getSource();
              alert(comp);
              AdfCustomEvent.queue(comp, "ServerEventToGetValue", {fvalue:comp.getSubmittedValue()}, true);
              evt.cancel();
            }
          
    

  • One more thing is to define server listener method in managed bean so that we can apply it to inputText at run time

  •     /**Server Listener - It will be called on execution of client side javascript
         * @param clientEvent
         */
        public void testServerListener(ClientEvent clientEvent) {
            //To get value passed from Client Event
            String val = clientEvent.getParameters().get("fvalue").toString();
            FacesMessage msg=new FacesMessage("Server Listener Called and value in inputText is - " + val);
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, msg);
           
        }
    

  • Now create clientListener/ServerListener programmatically and assign both to inputText
    Pass server listener method name along with managed bean name

  •         // Create new Client Listener and assign method name and type
            ClientListenerSet CL = new ClientListenerSet();
            CL.addListener("click", "demoJsFunction");
            //Add Server listener , assign client event name and resolve pre-defined serverlistener
            CL.addCustomServerListener("ServerEventToGetValue",
                                       getMethodExpression("#{viewScope.Testbean.testServerListener}"));
    
            // Add clientListener/ServeListener to inputText
            ui.setClientComponent(true);
            ui.setClientListeners(CL);
    

    Helper method to resolve expression-

        /**To Resolve ServerListener method
         * @param s
         * @return
         */
        public MethodExpression getMethodExpression(String s) {
    
            FacesContext fc = FacesContext.getCurrentInstance();
            ELContext elctx = fc.getELContext();
            ExpressionFactory elFactory = fc.getApplication().getExpressionFactory();
            MethodExpression methodExpr = elFactory.createMethodExpression(elctx, s, null, new Class[] {
                                                                           ClientEvent.class });
            return methodExpr;
    
        }
    

  • All done , now run application and check , click on button it will create a inputText
         now click on input text and see server listener is called :)

This is how we can apply javascript in programmatic created components
Cheers :) Happy Learning

Saturday 16 May 2015

Apply ActionListener to programmatically created buttons/link in ADF


This post is next in series of "Working with ADF Faces Components programmatically"
Previous posts are-
Creating dynamic layout (form and UI Component) using ADF Faces
Get Value from programmatically created components , Iterate over parent component to get child values in ADF Faces

Now this post is about applying ActionListener to a programmatically created button or link
Let's start (Jdev 12.13) -

  • First created a FusionWebApplication and a page in viewController project
  • Dropped a button on page , on this button action i will create a link programmatically and assign actionListener to it
  • To create new link i have added following code (described in previous posts)



  •     /**Method to add dynamically created component to a parent layout
         * @param parentUIComponent
         * @param childUIComponent
         */
        public void addComponent(UIComponent parentUIComponent, UIComponent childUIComponent) {
            parentUIComponent.getChildren().add(childUIComponent);
            AdfFacesContext.getCurrentInstance().addPartialTarget(parentUIComponent);
        }
    

           //Creating Link programmatically on button click     
            RichLink ui = new RichLink();
            ui.setId("li1");
            ui.setText("Programmatically Created Link");
            ui.setInlineStyle("font-weight:bold;");
            //Add this link to parent form layout
     //ParentGroupLayoutBind is the component binding of panelGroupLayout
            addComponent(getParentGroupLayoutBind(), ui);
    

  • After this we are able to create a new Link on click of button, now next is to assign ActionListener to this Link
    For this first i have to define an ActionListener method in bean. So i have added this 

  •     /**Action Listener to be applied on dynamically created button
         * @param actionEvent
         */
        public void actionForProgLink(ActionEvent actionEvent) {
            FacesMessage infoMsg = new FacesMessage("Action Listener Invoked");
            infoMsg.setSeverity(FacesMessage.SEVERITY_INFO);
            FacesContext.getCurrentInstance().addMessage(null, infoMsg);
        }
    

  • Now how to assign this ActionListener to that dynamically created Link?
    See the Code-

  •     /**Method to to resolve actionListener
         * @param actionName
         */
        private ActionListener getActionListener(String actionName) {
            //here Testbean is the name of ManagedBean
            MethodExpression methodExp = getMethodExpressionForAction("#{viewScope.Testbean." + actionName + "}");
            return new MethodExpressionActionListener(methodExp);
        }
    

    Helper method to resolve ActionListener-

        private MethodExpression getMethodExpressionForAction(String actionName) {
            Class[] argtypes = new Class[1];
            argtypes[0] = ActionEvent.class;
    
            FacesContext facesCtx = FacesContext.getCurrentInstance();
            Application app = facesCtx.getApplication();
            ExpressionFactory elFactory = app.getExpressionFactory();
            ELContext elContext = facesCtx.getELContext();
            return elFactory.createMethodExpression(elContext, actionName, null, argtypes);
        }
    

    Just pass the name of method to resolve it

       //Apply ActionListener on this dynamically created link 
        ui.addActionListener(getActionListener("actionForProgLink")); 
     
Now time to check , run application :)
First a button appears-


On click of this button a link is created -

Click on this link- programmatically assigned Action Listener is called

Cheers , Happy Learning :)