Search code examples
apache-flexmxml

Conditionally adding AdvancedDataGridColumn to AdvancedDataGrid


Following is the snippet from MXML file used for employee reports.

<mx:AdvancedDataGrid id="adgID" 
    dataProvider="{empList}"
    width="720" height="450"
    defaultLeafIcon="{null}" 
    selectionColor="#B5B2B2" rollOverColor="#6AB9F7"
    showEffect="{}">
    <mx:columns >               
        <mx:AdvancedDataGridColumn  dataField="empId" headerText="Employee ID"/>
        <mx:AdvancedDataGridColumn  dataField="dept" headerText="Department" />
        <mx:AdvancedDataGridColumn  dataField="empLastName" headerText="Last Name" />
        <mx:AdvancedDataGridColumn  dataField="empFirstName" headerText="First Name" />
    </mx:columns>
</mx:AdvancedDataGrid>

I want to use same MXML file for few different reports with some variation in columns. These 4 columns are common for all the reports but few of them have some extra reports. I'm able to change empList (dataProvider for the grid) but I am not sure how to add extra columns to this code so not everything is displayed for every report.

Basically I want to do this,

<mx:AdvancedDataGrid id="adgID" 
    dataProvider="{empList}"
    width="720" height="450"
    defaultLeafIcon="{null}" 
    selectionColor="#B5B2B2" rollOverColor="#6AB9F7"
    showEffect="{}">
    <mx:columns >               
        <mx:AdvancedDataGridColumn  dataField="empId" headerText="Employee ID"/>
        <mx:AdvancedDataGridColumn  dataField="dept" headerText="Department" />
        <mx:AdvancedDataGridColumn  dataField="empLastName" headerText="Last Name" />
        <mx:AdvancedDataGridColumn  dataField="empFirstName" headerText="First Name" />
    <!------------------------ Need to add this part ------------------------>  
        if(reportType == 1) {
            <mx:AdvancedDataGridColumn  dataField="empDOB" headerText="DOB" />
        }
        if(reportType == 2) {
            <mx:AdvancedDataGridColumn  dataField="empSalary" headerText="Salary" />
        }
    <!------------------------ Need to add this part ------------------------>
    </mx:columns>
</mx:AdvancedDataGrid>

How can I do this? We are using Flex 3. I have very basic knowledge of Flex.

Thanks for your help. -- AndyT


Solution

  • There are several different ways you can do this:

    • visible property on the column, this is by far the simplest solution, so long as your reportType is marked [Bindable]
    • remove the mxml column declarations and use a creationComplete event to a handler in a <script> tag to manually add your columns using the new .

    With Flex 4:

    • <declarations> top-level tag will allow you to keep the mxml and skip the tediousness of creating the columns which could be referenced via the id in the creationComplete handler.