Please disable your adblock and script blockers to view this page

Search this blog

Showing posts with label af:foreach. Show all posts
Showing posts with label af:foreach. Show all posts

Thursday 16 April 2015

Build selectOneChoice to show hierarchical (tree style) data programmatically in ADF

This post is based on an old article from Frank Nimphius How - to build a select one choice displaying hierarchical selection data

This article is about showing tree structure data in af:selectOneChoice component using ADF BC , it makes use of tree binding and af:forEach
Same concept i have used to populate data from managed bean using List data structure

Let's see the implementation part - how to populate tree style selectOneChoice programatically ?

First we have to design a Java Bean class in such a way that it can hold  master -detail type of data

A class that represents a List for Parent Values
                          ======> A list of same type to hold Child Values

See bean class code-

import java.util.ArrayList;
import java.util.List;

public class Seasons {
    public Seasons(String name) {
        this.name = name; // To Store Header Values (Storing Seasons Name :))
    }
    // Season and Charater Name
    private String name;
    // To Store Detail Values (Storing Season's Charatcers)
    private List<Seasons> characters = new <Seasons>ArrayList();

    public void setCharacters(List<Seasons> empDet) {
        this.characters = empDet;
    }

    public List<Seasons> getCharacters() {
        return characters;
    }


    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
    // This methods directly add characters value in list
    public void addCharaters(Seasons employee) {
        characters.add(employee);
    }
}

Now how to use this bean in managed bean to add records, i have written code in constructor to populate values on class load




    // Master List to populate data in selectOnce choice
    List<Seasons> seasonList = new ArrayList<Seasons>();

    public void setSeasonList(List<Seasons> seasonList) {
        this.seasonList = seasonList;
    }

    public List<Seasons> getSeasonList() {
        return seasonList;
    }
    //Constructor of Managed Bean to populate data on page load (you can move this code )
    public TreeStyleLovBean() {
        super();
        // Creating tree for Seasons and Characters details
        // Adding Master Values (seasons)
        Seasons season1 = new Seasons("Game of Thrones");

        // Adding Detail Values (Child Node-Characters)
        Seasons character = new Seasons("Tywin Lannister");
        season1.addCharaters(character);
        character = new Seasons("Tyrion Lannister");
        season1.addCharaters(character);
        character = new Seasons("Jaime Lannister");
        season1.addCharaters(character);
        character = new Seasons("Cersie Lannister");
        season1.addCharaters(character);
        character = new Seasons("Ned Stark");
        season1.addCharaters(character);

        // Adding Master Values (seasons)
        Seasons season2 = new Seasons("Arrow");

        // Adding Detail Values (Child Node-Characters)
        character = new Seasons("Oliver Queen");
        season2.addCharaters(character);
        character = new Seasons("Moira Queen");
        season2.addCharaters(character);
        character = new Seasons("Laurel Lance");
        season2.addCharaters(character);
        character = new Seasons("Sara Lance");
        season2.addCharaters(character);

        // Adding Master Values (seasons)
        Seasons season3 = new Seasons("Vikings");

        // Adding Detail Values (Child Node-Characters)
        character = new Seasons("Ragnar Lothrak");
        season3.addCharaters(character);

        // Adding Master Values (seasons)
        Seasons season4 = new Seasons("The Flash");

        // Adding Detail Values (Child Node-Characters)
        character = new Seasons("Barry Allen");
        season4.addCharaters(character);
        character = new Seasons("Harisson Wells");
        season4.addCharaters(character);
        character = new Seasons("Iris West");
        season4.addCharaters(character);
        character = new Seasons("Joe");
        season4.addCharaters(character);

        // Adding all list to topList
        seasonList.add(season1);
        seasonList.add(season2);
        seasonList.add(season3);
        seasonList.add(season4);

    }
how to bind this managed bean to selectOneChoice ? i have used same concept as described in Frank's article using af:forEach


<af:selectOneChoice id="selectBox" label="Choose Character" valuePassThru="true"
                                        styleClass="employeeSelectBox" contentStyle="width:150px;"
                                        binding="#{viewScope.TreeStyleLovBean.selectOneValueBind}">
                        <af:forEach items="#{viewScope.TreeStyleLovBean.seasonList}" var="seasonNm">
                            <af:selectItem label="#{seasonNm.name}" disabled="true" id="si1"/>
                            <af:forEach items="#{seasonNm.characters}" var="characterNm">
                                <af:selectItem label="#{characterNm.name}" value="#{characterNm.name}" id="si2"/>
                            </af:forEach>
                        </af:forEach>
                    </af:selectOneChoice>

you can see here that first forEach is populated from master list and iterates over list of seasons and first selectItem show season's name
the inner forEach makes used of character list that is defined in Java Bean class and stores season wise character's name
Rest is same - a CSS is used to differentiate color and alignment of parent and child records (same as Frank's article)


<f:facet name="metaContainer">
                <af:group>
                    <![CDATA[
<style>
.employeeSelectBox option{text-indent:15px;color:darkgreen;}
.employeeSelectBox option[disabled]{color:red; background-color:#dddddd; 
font-weight: bold; text-indent:0px}
</style>
]]>
                </af:group>
            </f:facet>

Now run this application - see how it appears on page



It looks quite good :) to get selected value in bean just use componentBinding.getValue();

Sample ADF Application-Download (Jdev 12.1.3)
Cheers , Happy Learning 

Monday 16 February 2015

Working with af:iterator and af:forEach programmatically (Add and delete records using List)

In previous post Working with af:iterator and af:forEach programmatically (Populate values using POJO from Managed Bean) we saw that how can we populate record from a List to af:iterator and af:forEach (ADF Faces Component)

So this post is about adding and deleting of records from List while List is presented using af:iterator.
here i am extending previous post and using same sample application



Added two fields and button on page to add records 


<af:panelFormLayout id="pfl1" rows="1">
                    <af:inputText label="Name" id="it1" binding="#{viewScope.PopulateIteratorBean.nameBind}"/>
                    <af:inputText label="Department" id="it2" binding="#{viewScope.PopulateIteratorBean.deptNameBind}"/>
                    <af:button text="Add" id="b1"
                               actionListener="#{viewScope.PopulateIteratorBean.addNewRecordAction}"/>
                </af:panelFormLayout>




and on this button action simply added both attributes to List and added partial trigger of button to af:iterator to refresh it


    // Component binding to access inputValue from page
    
    private RichInputText nameBind;
    private RichInputText deptNameBind;
    
    public void setNameBind(RichInputText nameBind) {
        this.nameBind = nameBind;
    }

    public RichInputText getNameBind() {
        return nameBind;
    }

    public void setDeptNameBind(RichInputText deptNameBind) {
        this.deptNameBind = deptNameBind;
    }

    public RichInputText getDeptNameBind() {
        return deptNameBind;
    }

    /**Method to add record in List and show on page using af:iterator and af:forEach
     * @param actionEvent
     */
    public void addNewRecordAction(ActionEvent actionEvent) {
        if (nameBind.getValue() != null && deptNameBind.getValue() != null) {
            EmployeeDet obj = new EmployeeDet(nameBind.getValue().toString(), deptNameBind.getValue().toString());
            employeeDetail.add(obj);
            
        }
    }


On page - add a new record (record added in List and appeared in iterator as well)


So it is quite simple to add records but deletion of record is a bit tricky but not difficult at all :)
Let's see this-
For deleting record i have added a delete link inside iterator so that it should appear for each record as you can see in snap (above)
Here question is that how to know that which record should be deleted  ?

So for this i have added a f:attribute tag to link , this attribute contains the value of current item of iterator



f:attribute derives it's value from var of af:iterator/af:forEach, this var represents each item of List
Now on delete button's action - get the current item and remove it from List


    /**Method to delete selected record
     * @param actionEvent
     */
    public void deleteRecordAction(ActionEvent actionEvent) {
        //Get value from f:attribute (current item)
       Object itemVal= actionEvent.getComponent().getAttributes().get("itemVal");
       //Remove selected item from List
       employeeDetail.remove(itemVal);
    }

After deleting records

Sample ADF Application- Download

Tuesday 10 February 2015

Working with af:iterator and af:forEach programmatically (Populate values using POJO from Managed Bean)


This is another post about Working programmatically with ADF (populating af:iterator and af:forEach programmatically )

Previously i have posted about populating af:iterator and af:forEach using ADF BC and binding layer to show master-detail relation
Implementing master/detail tree relation using af:Iterator and af:forEach for better UI designs - Oracle ADF

For this post i am populating employee name and it's department name using List datastructure ,to get and set value of attributes

Created a java bean class , it has 2 variable for both attributes




public class EmployeeDet {
    public EmployeeDet(String name, String deptName) {
        this.name = name;
        this.deptName = deptName;
    }
    //Attribute to display EmployeeName and Department Name
    private String name;
    private String deptName;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }

    public String getDeptName() {
        return deptName;
    }
}

Next step is to create a managed bean to populate data in af:iterator and af:forEach , this managed bean makes use of
EmployeeDet 
java bean class to add data in same format for all items of iterator and forEach. A List data structure is used to pass all values to iterator. See code of managed bean 




    //Constructor-populate default records
    public PopulateIteratorBean() {

        EmployeeDet obj = new EmployeeDet("Ashish Awasthi", "Oracle ADF");
        employeeDetail.add(obj);
        obj = new EmployeeDet("Alex Smith", "Java");
        employeeDetail.add(obj);
        obj = new EmployeeDet("James S", "PHP");
        employeeDetail.add(obj);
    }
    //ArrayList to poplate data in af:iterator and af:forEach
    private List<EmployeeDet> employeeDetail = new ArrayList();

    public void setEmployeeDetail(List<EmployeeDet> employeeDetail) {
        this.employeeDetail = employeeDetail;
    }

    public List<EmployeeDet> getEmployeeDetail() {

        return employeeDetail;
    }

Now drop af:iterator on page and set it's properties like value, var etc


using var reference of iterator , set value in output text to show Employee Name and DepartmentName , see XML source of af:iterator


<af:panelGroupLayout id="pgl1" layout="horizontal">
                        <af:iterator id="i1" value="#{viewScope.PopulateIteratorBean.employeeDetail}" var="item">
                            <af:panelBox id="pb2" showDisclosure="false">
                                <f:facet name="toolbar"/>
                                <af:panelGroupLayout id="pgl3" layout="horizontal">
                                    <af:outputText value="#{item.name}" id="ot1"
                                                   inlineStyle="font-weight:bold; font-size:medium; color:#0572ce;;"/>
                                    <af:spacer width="2" height="0" id="s1"/>
                                    <af:outputText value="(#{item.deptName})" id="ot2"
                                                   inlineStyle="font-weight:bold;font-size:small;color:red;"/>
                                </af:panelGroupLayout>
                            </af:panelBox>
                        </af:iterator>
                    </af:panelGroupLayout>  

on running it looks like this-


do same for af:forEach


<af:panelGroupLayout id="pgl2" layout="horizontal">
                        <af:forEach items="#{viewScope.PopulateIteratorBean.employeeDetail}" var="feach">
                            <af:showDetailHeader text="#{feach.deptName}" disclosed="true" id="sdh1">
                                <af:outputText value="#{feach.name}" id="ot3"
                                               inlineStyle="font-weight:bold; font-size:medium; color:#0572ce;;"/>
                            </af:showDetailHeader>
                        </af:forEach>
                    </af:panelGroupLayout>

on running it looks like this-
 Sample ADF Application-Download
Thanks, Happy Learning :)

Thursday 28 August 2014

Create taskFlow and region binding at run-time , show n numbers of regions using multiTaskFlow- Oracle ADF

This is very specific development requirement to create taskFlow and region binding at run-time to show n numbers of region in page
In this case initially you don't know how much regions required in page as it depends on user activity .

you can see in http://irctc.co.in/ (Indian Railways) site
when user search for a train and check berth availability then a tab is generated at run-time with berth and fare details and it continues for each action , every time a new tab with new information is generated (n- number of tab and taskFlow)

A very good article is published in Oracle Magazine (July – August 2014) by Frank Nimphius on this requirement , article contains very good description of each and every step and a sample application with whole functionality
I found it very interesting and good so giving a quick overview of TaskFlow on Fly

this functionality is implemented using multiTaskFlow element that uses taskFlow binding from managed bean , taskFlow bindings in managed bean created using TaskFlowBindingAttributes
this class is used to set all properties of taskFlow binding at runtime



See Oracle docs (TaskFlowBindingAttributes)-
Set of attributes that define a TaskFlowBinding object. The taskFlowList attribute of the multiTaskFlow element of the page definition uses a list of object of this type to describe each taskflowBinding that the multiTaskflow binding contains. The order of this list defines the order of the region objects in the multiTaskflow binding. 

So in this post i am using Departments and Employees table of HR Schema(Oracle) to create business components for Model part


Create viewCriteria in both viewObjects (Departments and Employees) to filter data using DepartmentId




Applied viewCriteria to viewObject at AM level (Edit Vo instance and shuttle viewCriteria to selected side)
After this created methods in AMImpl class to set value in both viewCriteria's bind variables


    /**Method to filter Department ViewObject
     * @param deptId
     */
    public void filterDepartmentData(Integer deptId) {
        this.getDepartments1().setNamedWhereClauseParam("BindDeptId", deptId);
        this.getDepartments1().executeQuery();

    }

    /**Method to filter Employees Data
     * @param deptId
     */
    public void filterEmployeesData(Integer deptId) {
        this.getEmployees1().setNamedWhereClauseParam("BindDeptId", deptId);
        this.getEmployees1().executeQuery();

    }

Expose both methods to use in clientInterface

Now viewController part-

Created two bounded taskFlow with one input parameter for DepartmentId (this id will be used to filter Departments and Employess viewObject)
One for Departments and Second for Employees-

First taskFlow has a .jsff (facelets) page that has Departments viewObject as a form , just to show date with navigation buttons
filterDepartmentData method of AMImpl is used as Default Activity of this taskFlow
to filter data before entering in page
 
 
 

Second taskFlow has a .jsff (facelets) page that has Employees viewObject as a table
filterEmployeesData method of AMImpl is used as Default Activity of this taskFlow
to filter data before entering in page



Now basic configuration is complete, model is ready and bounded taskFlows are ready
then create a jsf page and manged bean (pageFlowScope) in adfc-config.xml, this page will make use of these two bounded taskFlows  and managed bean is responsible to generate taskFlow binding at runtime

Next Step is to prepare manged bean to hold taskFlowBinding-
Create a List of type TaskFlowBindingAttributes and it's accessors


import oracle.adf.controller.binding.TaskFlowBindingAttributes;    
private List<TaskFlowBindingAttributes> taskFlowBinding = new ArrayList<TaskFlowBindingAttributes>(5);

    public void setTaskFlowBinding(List<TaskFlowBindingAttributes> taskFlowBinding) {
        this.taskFlowBinding = taskFlowBinding;
    }

    public List<TaskFlowBindingAttributes> getTaskFlowBinding() {
        return taskFlowBinding;
    }

Create multiTaskFlow binding in executables of pgae-

  • Open jsf page, click on bindings tab of page editor
  • click on green plus icon of executables section
  • Select ADF TaskFlow Bindings in category and select multiTaskFlow


  • click on ok and provide an unique value for id attribute and reference of List created in managed bean as value for taskFlowList attribute


  • Configuration of  multiTaskFlow for this page is complete and now time to design page to render multiple regions. For this purpose add af:ForEach and a region inside it, forEach is responsible to add regions at run-time. here a little change i am using panelTabbed  to create tab at runtime and inside tab there will be region 
  • See this xml code- here nothing simple panelTabbed and forEach iterates over to list to identify number of items and varStatus of forEach is used to create id of showDetailItem at runtime as id must be unique. regionModel is referenced from var attributes of forEach as part of taskFlowBinding 

  •  <af:panelTabbed position="above" id="pt1" partialTriggers="b1">
                <af:forEach items="#{bindings.mtf1.taskFlowBindingList}" var="multiTF" varStatus="vs">
                   <af:showDetailItem id="Tab#{vs.index+1}" text="#{multiTF.name}" partialTriggers="b1">
                      <af:region value="#{multiTF.regionModel}" id="r1#{vs.index}" partialTriggers="::b1"/>
                   </af:showDetailItem>
                </af:forEach>
             </af:panelTabbed>
    

  • Now page is ready to show unknown (n) number of regions, here i am using two list and a button on page First List is of all departments and second one is static list to select information type (if user want to see Only Departments or Departments Wise Employees) and button to execute and add taskFlow from managed bean as per selected Department and 
  • Again a map is created in managed bean to store input parameters for taskFlow and it will used while setting and creating taskFlowBinding

  •     HashMap<String, Object> tfParam = new HashMap<String, Object>();
        public void setTfParam(HashMap<String, Object> tfParam) {
            this.tfParam = tfParam;
        }
    
        public HashMap<String, Object> getTfParam() {
            return tfParam;
        }
    

  • finally we will create taskFlow binding and set properties on button click (actionEvent of button), See this code-

  •     /**Method to create and set properties in TaskFlowBinding
         * @param actionEvent
         */
        public void displayDepartmentAction(ActionEvent actionEvent) {
            //Clear List to show newly created regions only
            taskFlowBinding.clear();
            System.out.println("List Cleared -Size>" + taskFlowBinding.size());
            //Check that user selects value in both List (Uses component binding to check)
            if (deptIdBindVal.getValue() != null && showTypeBind.getValue() != null) {
                //Put value in TaskFLow Parameter map, deptIdBindVal is binding of list of departments on page
                tfParam.put("DeptIdParam", deptIdBindVal.getValue());
    
                //Only Shows Departments taskFlow, if user selectes "Only Departments"
                if ("Only Departments".equalsIgnoreCase(showTypeBind.getValue().toString())) {
                    //Setting taskFlow properties
                    TaskFlowBindingAttributes tfAttr = new TaskFlowBindingAttributes();
                    //Creating Unique Id
                    tfAttr.setId("Department_" + deptIdBindVal.getValue());
                    //See bounded taskFlow name in WEB-INF and use here
                    tfAttr.setTaskFlowId(new TaskFlowId("/WEB-INF/DepartmentsBTF.xml", "DepartmentsBTF"));
                    //This EL refers parameter map created in this managedBean
                    tfAttr.setParametersMap("#{pageFlowScope.MultiTaskFlowBean.tfParam}");
                    //Finally add taskFlow to List
                    taskFlowBinding.add(tfAttr);
                } else { // Show both Departments and Employees
                    //Creating Departments TaskFlow binding
                    TaskFlowBindingAttributes tfAttr = new TaskFlowBindingAttributes();
                    tfAttr.setId("Department_" + deptIdBindVal.getValue());
                    tfAttr.setTaskFlowId(new TaskFlowId("/WEB-INF/DepartmentsBTF.xml", "DepartmentsBTF"));
                    tfAttr.setParametersMap("#{pageFlowScope.MultiTaskFlowBean.tfParam}");
                    taskFlowBinding.add(tfAttr);
                    //Creating Employee TaskFlow biniding
                    tfAttr = new TaskFlowBindingAttributes();
                    tfAttr.setId("Employees_" + deptIdBindVal.getValue());
                    tfAttr.setTaskFlowId(new TaskFlowId("/WEB-INF/EmployeesBTF.xml", "EmployeesBTF"));
                    tfAttr.setParametersMap("#{pageFlowScope.MultiTaskFlowBean.tfParam}");
                    taskFlowBinding.add(tfAttr);
                }
            }
        }
    

  • So Application with multiTaskFlow is ready , in this post i have used these two bounded taskFlow to show in two tabs at run-time, in same way you can call multiple TFs or a single taskFlow multiple time. Now runt application and see how it works

Initial page with two lists


Select Department and show type -click on button


Select Department and show type -click on button


  • Refer this post Region Extreme: Multi-Task-Flow Binding to learn more about multiTaskFlow binding. In this Frank also told about how to use dynamic viewObject instance to show different data at run-time, because if we use same instance of viewObject in multiple taskFlow at same time then it will not maintain state for each region to it is necessary to use dynamic instance and it's binding in pageDef
  • Read more about regions and taskFlows- Using Task Flows as Regions
Thanks - Happy Learning :) Sample ADF Application

Monday 23 September 2013

Dynamically enable or disable items of ADF bound List (af:selectOneChoice) -Oracle ADF

Hello All,
This tutorial is about a requirement of conditionally enabling/disabling items (values) of adf bound List (af:selectOneChoice) component
here i am taking reference of default HR Schema (Departments and Location table )

See the steps-
  • Create a Fusion Web Application and business components using both tables
  •  Now create List of Values (Lov) on locationId of departments VO from Location VO
  • Set List Attribute to LocationId and for UI city will be shown
  • Now Drag Departments VO from Data Control on page as a form
  •  Select LocationId list field and delete f:selectItems from it, now drag af:selectItem as child of af:selectOneChoice and surround it with af:forEach 



  • Add tree binding of Location ViewObject to page bindings in order to populate list items using forEach
  •  Now select af:forEach and set its property and variable name, as we have to iterate through Location VO for list items
  •  Again select af:selectItem and set its value and label property using forEach variable's  
  • Now run your application, and see that list box is ready with values
  • Now we have to disable its values as a condition basis, i have written an Expression on af:selectItem's disabled property


  • I have written condition for DepartmentId 100 and 110, see in source of page

  • <af:selectOneChoice value="#{bindings.LocationId.inputValue}" label="#{bindings.LocationId.label}"
                                            required="#{bindings.LocationId.hints.mandatory}"
                                            shortDesc="#{bindings.LocationId.hints.tooltip}" id="soc1"
                                            contentStyle="width:150px;color:red;">
                            <af:forEach items="#{bindings.Locations1.rangeSet}" var="list">
                                <af:selectItem label="#{list.City}" id="si1" value="#{list.LocationId}"
                                               disabled="#{ (bindings.DepartmentId.inputValue==100 and (list.LocationId==1000 || list.LocationId==1300)) || (bindings.DepartmentId.inputValue==110 and (list.LocationId==1500 || list.LocationId==1600 || list.LocationId==1700 || list.LocationId==1800 || list.LocationId==1900))}"/>
                            </af:forEach>
                        </af:selectOneChoice>
    

  • Now value given in Expression for Location Id will be disabled for given Department
  • Run your page and select DepartmentId 100 and 110 to see disabled list items

 Download Sample App Cheers :-)