function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ekmekm 

Flex: Query parent and child fields from SalesForce

Hi,

I am attempting to query data from the Accounts table as well as several child fields from the Events table. I can successfully query from each  individually but am not having success in combining them into one dataprovider which populates a datagrid.
I haven't seen an example of this, so if someone could point me in the right direction, I would great appreciate it. FYI, both tmp and eventNameDateTime are bindable arrayCollections.

Thanks,

Errol

private function displayEditMeetingSearchResults():void {
                             
                apex.query("Select Id, AccountNumber, Name, (Select Event.AccountId, Event.ActivityDate, Event.Id, Event.Type From Account.Events) from Account", new AsyncResponder
                (
                    function(qr:QueryResult):void
                    {
                        if (qr.size > 0)
                        {
                            tmp = qr.records;
                            //eventNameDateTime = qr.records;
                            eventNameDateTime = tmp.getItemAt(0).Events.records;
           
                        }
                    },
                    handleFault)
                );
            }
csharmacsharma
Hey is your issue resolved, I have the same problem! 
csharmacsharma
The issue with me is that How would I populate a datagrid with both parents and chidlren considering that P-C have 1..n association.
e.g. every account can have n opportunities. so how to get both 1) account as well as 2) opportunities in the same datagrid, even if i have to use advanced datagrid.
I am stuck at the same point as above as I couldnot find a way to assign the complete child set into one arraycollection?

Any way out??


ekmekm

Hey there,

Thanks for responding. I still haven't had any luck in solving this either. I also tried running two separate queries (I have another post on that) but still no luck. I believe we're essentially attempting to do the same thing: populate a datagrid with data from a field in a parent table and a field in a chid table, essentially data from 2 tables into one datagrid.

Would be great if someone could point us in the right direction. I'm still working on it though.

ekmekm
Hey,

A solution was suggested in another post I had made where I was trying to run a separate subquery. (Thanks werewolf).

Here's the solution: Hope this helps.

[Bindable]
    public var ar:ArrayCollection = new ArrayCollection();
   
    private function queryAccountManagerEdit1():void
      {
        currentState="searchAccountManagerEdit";
        var acc:SObject = new SObject('AccountContactRole');
        apex.query("Select a.Id, a.Role, a.Contact.Id, a.Contact.Name from AccountContactRole a where a.Role = 'Decision-maker'",  
            new AsyncResponder(function (qr:QueryResult):void
              {
                for (var j:int=0;j<qr.records.length;j++)
                    {
                    ar.addItem(  { Role:qr.records[j].Role, Name:qr.records[j].Contact.Name } );
                    //ar.addItem(  { Role:qr.records[j].Role } );
                }
                // create the columns and specify the order
                dgSearchAccountManagerEdit.columns = [ new DataGridColumn('Name'), new DataGridColumn('Role') ];
                dgSearchAccountManagerEdit.dataProvider = ar;    //assign the array as the data provider
                }
               ) // closes new AsyncResponder(function (qr:QueryResult):void
        ); //closes 1st apex query
    }  
csharmacsharma
Hey thanks a lot,
I have solved the issue and m now able to populate the advanced data grid from both parent and child. actually earlier i wasnt adding opportunities.records in the array collection and got confused of ways to access the children...which all were wrong conceptually :D !!

The code goes as follows, hope it might be helpful:

//inisde script

private function loadData(o:Object=null):void {
                var m1:Array=new Array();
                var m2:Array=new Array();


                apex.query("SELECT Name, (Select Opportunity.Name, Opportunity.StageName, Opportunity.Probability, Opportunity.Amount, Opportunity.ExpectedRevenue, Opportunity.CloseDate FROM Account.Opportunities) FROM Account",new AsyncResponder(handleDataFromApex
                    ,handleFault)
                );
            }
       
            private function handleDataFromApex(qr:QueryResult):void{
                accountList = qr.records;
               
               
                //trace(accountList[2].Opportunities.records.length);
                for(var i:int=0;i<qr.records.length;i++){
                   
                    if(accountList[i].Opportunities != null){                     
                        bl.addItem({ Name:accountList[i].Name, bache:accountList[i].Opportunities.records});
                    }//if ends here
                                       
                }//outside for(i) ends here
               
            }//end of handldatafromapex function


//mxml

<mx:AdvancedDataGrid id="adg" width="100%" color="#000000">
                     <mx:dataProvider>
                        <mx:HierarchicalData source="{bl}" childrenField="bache"/>
                        </mx:dataProvider>
                 
                    <mx:columns>
                        <mx:AdvancedDataGridColumn dataField="Name"/>
                        <mx:AdvancedDataGridColumn dataField="StageName"/>
                        <mx:AdvancedDataGridColumn dataField="Probability" headerText="Probibility (%)"/>
                        <mx:AdvancedDataGridColumn dataField="Amount" headerText="Amount (USD)"/>
                        <mx:AdvancedDataGridColumn dataField="ExpectedRevenue" headerText="Expected Revenue (USD)"/>
                        <mx:AdvancedDataGridColumn dataField="CloseDate" headerText="Close Date (USD)"/>
                       
                    </mx:columns>   
       </mx:AdvancedDataGrid>
reshmareshma
Hi just try this way

[Bindable]

private var dataList:ArrayCollection = new ArrayCollection();

private function displayEditMeetingSearchResults():void {                          
                apex.query("Select Id, AccountNumber, Name, (Select Event.AccountId, Event.ActivityDate, Event.Id, Event.Type From Account.Events) from Account", new AsyncResponder
                (
                    function(qr:QueryResult):void
                    {
                        if (qr.size > 0)
                        {
                          datalist=qr.records;            
                        }
                    },
                    handleFault)
                ;
            }
to populate in datagrid

<mx:DataGrid x="453" y="84" height="188" width="379" dataProvider="{dataList}">

<mx:columns>

 

<mx:DataGridColumn dataField="Id" headerText="Id"/>

<mx:DataGridColumn dataField="GWP100__c" headerText="GWP100"/>

<mx:DataGridColumn dataField="AccountNumber" headerText="AccountNumber"/>

<mx:DataGridColumn dataField="Name" headerText="Name"/>

</mx:columns>

</mx:DataGrid>

 

Regards,

Wipro Technologies

MohanaGopalMohanaGopal

Hi..

   I have one issue.. If  apex.query()  in Flex returns null value means how to handle it..

In my case it shows "TypeError: Error #1009: Cannot access a property or method of a null object reference."

which query return null value in Salesforce. That is record length is 0. But in flex I dont know why it couldnt handle null value.. If my flex query return 1 or more records means it works properly..

        Its shows error when my query doesnt return any value, even i could nt get queryresult for it.

How to handle it..

ekmekm
Hi,

What about putting your apex.query() inside a try/catch? Or placing a where "field" != null inside your query?
FYI, something I discovered is you can't use (error:Error) because Error conflicts with the SalesForce APIs. Just use something like catch(errorObject:Object) instead.

Hope this helps.
MohanaGopalMohanaGopal

This is my query

         This query works fine when its return some records.. If its return null (0 Records) means its shows 1009 error.. If  I click dismiss all or Continue button, it continue to work my code..

Here I need to perform some operations when its null..
Here I am using qr.size==0 condition..
my code is
if(qr.size==0)
{
Alert.show("No records");
Alert.show("Inside");
some operations
}    
 It returns only alert message "No records"... Remaining operations and another alert operation doesnt perform..
 
Whats wrong in my code..
 

private function changeAreaCombo(event:Event):void

{

var AreaName:String=event.currentTarget.selectedItem.label;

AreaName=AreaName.toString();

apex.query("select Id from Area__c where Name='"+AreaName+"'",

new AsyncResponder(

function (qr:QueryResult):void

{

apex.query("select Name,Actual_kW_Saved__c,Actual_kWh_Saved__c,Adjusted_kW_Saved__c,Adjusted_kWh_Saved__c,Net_kWh_Saved__c,Rebate__c,Utility_Rate__c,Labor_Cost__c,Install_Cost__c from Calculated_Lighting_Measures__c where Area__c='"+qr.records[0].Id+"' and Current_Project__c='"+Application.application.parameters.project_id+"'",

new AsyncResponder(

function (qr1:QueryResult):void

{

var emptyCell:String="";

var f:Number=qr1.size;

var acArea:ArrayCollection=new ArrayCollection();

if(f==0)

{

Alert.show("No Records Here");

acArea.addItem({'Actual kWh Saved':emptyCell,'Actual kW Saved':emptyCell,'Adjusted kWh Saved':emptyCell,'Adjusted kW Saved':emptyCell,'Install Cost':emptyCell,'Labor Cost':emptyCell,'Net kWh Saved':emptyCell,'Task Rebate':emptyCell,'Utility Savings':emptyCell});// It doesnt perform.. Here I try to clear the datagrid columns

Alert.show("Empty Datagrid"); // This message not shown..

}

for(var j:int=0;j<qr1.records.length;j++)

{

acArea.addItem({'Actual kWh Saved':qr1.records[j].Actual_kWh_Saved__c,'Actual kW Saved':qr1.records[j].Actual_kW_Saved__c,'Adjusted kWh Saved':qr1.records[j].Adjusted_kWh_Saved__c,'Adjusted kW Saved':qr1.records[j].Adjusted_kW_Saved__c,'Install Cost':qr1.records[j].Install_Cost__c,'Labor Cost':qr1.records[j].Labor_Cost__c,'Net kWh Saved':qr1.records[j].Net_kWh_Saved__c,'Task Rebate':qr1.records[j].Rebate__c,'Utility Savings':qr1.records[j].Utility_Rate__c});

}

bg1.columns=[new DataGridColumn("Actual kWh Saved"),new DataGridColumn("Actual kW Saved"),new DataGridColumn("Adjusted kWh Saved"),new DataGridColumn("Adjusted kW Saved"),new DataGridColumn("Install Cost"),new DataGridColumn("Labor Cost"),new DataGridColumn("Net kWh Saved"),new DataGridColumn("Task Rebate"),new DataGridColumn("Utility Savings")];

bg1.dataProvider=acArea;

},

function (fault:Object):void

{

Alert.show("Query Failed");

}

));

},

function (fault:Object):void{

}

));

}

 
KRSKRS

Hi,

 

 I was trying to try a similair type of Requirement. When i try running it,I am stuck up with an error say '1120 : Access of Undefined Property'.I am pasting my code below.Any help to this are highly appreciated.

 

I had made the Line as GREEN Colored and Bolded in the below code for which the error is showing

 

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:salesforce="http://www.salesforce.com/" creationComplete="login()" viewSourceURL="srcview/index.html">

<salesforce:Connection id="connection"/>

<mx:Script>

<![CDATA[

import mx.collections.ArrayCollection;

import mx.utils.*;

import com.salesforce.objects.SObject;

import com.salesforce.results.QueryResult;

import com.salesforce.AsyncResponder; import com.salesforce.objects.LoginRequest;

 

 

private function login():void {

var lr:LoginRequest = new LoginRequest();

lr.server_url = parameters.server_url;

lr.username = "username";

lr.password = "password";

lr.callback = new AsyncResponder(getRecords);

//getRecords();

 

connection.login(lr);

 

}

 

 

[Bindable] public var ar:ArrayCollection = new ArrayCollection();

 

private function getRecords(o:Object=null):void

{

connection.query("SELECT Name,(Select Child_Products__c.Name, Child_Products__c.X2006_Total_GSV_000__c, Child_Products__c.X2007_Total_GSV_000__c) FROM Parent_Product__c",new AsyncResponder(handleDataFromApex));

 

}

 

private function handleDataFromApex(qr:QueryResult):void{

ar = qr.records;

 

for(var i:int=0;i<qr.records.length;i++){

 

if(ar[i].Child_Products__c != null){

 

bl.addItem({Name:ar[i].Name, bache:ar[i].Child_Products__c.records});

}

 

}

}

 

 

]]>

 

</mx:Script>

 

 

<mx:AdvancedDataGrid id="adg1" designViewDataType="tree" width="720" height="764">

<mx:dataProvider>

<mx:HierarchicalData source="{bl}" childrenField="{bache}"/>

</mx:dataProvider>

 

<mx:groupedColumns>

<mx:AdvancedDataGridColumn id="estCol" headerText="Name" dataField="Name"/>

<mx:AdvancedDataGridColumn headerText="2006 Total GSV(000)" dataField="X2006_Total_GSV_000__c"/>

<mx:AdvancedDataGridColumn headerText="2007 Total GSV(000)" dataField="X2007_Total_GSV_000__c"/>

</mx:groupedColumns>

 

 

 

</mx:AdvancedDataGrid>

 

</mx:Application>