• David Roberts 4
  • NEWBIE
  • 169 Points
  • Member since 2015
  • Business Development manager
  • Logicom Virtual Worlds

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 2
    Likes Given
  • 18
    Questions
  • 226
    Replies
I found some references to displaying report data in Lightning but have got stuck.
I'm using a simple Account Visit report which has a group but I don't find it with the code I have. Basically, I see the results in a JSON but can't interpret them into my chart.
Here's my class:
public class ReportViaApexController {
    //https://absyz.com/displaying-standard-report-data-in-lightning-component/
    //https://cloudanswers.com/blog/run-salesforce-reports-in-apex
    //https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_analytics_report_data.htm
    //https://www.linkedin.com/pulse/reports-apex-its-use-vijayakumar-vm
    //
    @AuraEnabled
    public static string getReportPlanned(String AccId){
        //Report repRec = [SELECT Id, Name, DeveloperName FROM Report WHERE DeveloperName LIKE 'Catalogue_Summary%'];
        Report repRec = [SELECT Id, Name, DeveloperName FROM Report WHERE DeveloperName LIKE 'Visit_Reports_by_accounts%'];
        //00O8E000000HkNvUAK
        //
        string reportPlannedId=repRec.Id;
        string filterId=String.valueOf(AccId).substring(0, 15);
        // Retrieves report metadata
        Reports.ReportDescribeResult describe = Reports.ReportManager.describeReport(reportPlannedId);
        Reports.ReportMetadata reportMd = describe.getReportMetadata();
        // Add/Override filters
        Reports.ReportFilter filterlist = reportMd.getReportFilters()[0];
        filterlist .setValue(filterId);
        //filterlist .setValue('In Progress');
        //and Run report
        Reports.ReportResults reportResult = Reports.ReportManager.runReport(reportPlannedId,reportMd);
        system.debug('ReportResultsJSON '+JSON.serialize(reportResult));
        
        MAP<String,Reports.ReportFact> summarizedRows=reportResult.getFactMap();
        
        System.debug('summarizedRows: ' + summarizedRows);
        
        // Get the first down-grouping in the report
        Reports.Dimension dim = reportResult.getGroupingsDown();
        System.debug('dim: ' + dim);
        Reports.GroupingValue groupingVal = dim.getGroupings()[0];
        System.debug('Key: ' + groupingVal.getKey());
        System.debug('Label: ' + groupingVal.getLabel());
        System.debug('Value: ' + groupingVal.getValue());
        
        // Construct a fact map key, using the grouping key value
        String factMapKey = groupingVal.getKey() + '!T';
        
        // Get the fact map from the report results
        Reports.ReportFactWithDetails factDetails =
            (Reports.ReportFactWithDetails)reportResult.getFactMap().get(factMapKey);
        
        // Get the first summary amount from the fact map
        Reports.SummaryValue sumVal = factDetails.getAggregates()[0];
        System.debug('Summary Value: ' + sumVal.getLabel());
        
        // Get the field value from the first data cell of the first row of the report
        Reports.ReportDetailRow detailRow = factDetails.getRows()[0];
        System.debug(detailRow.getDataCells()[0].getLabel());
        
        
        
        return JSON.serialize(reportResult);
    }//Getreportplanned

}//ReportViaApexController

My component from the bundle ReportViaApex:
<aura:component controller="ReportViaApexController" access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:lightningQuickAction">

    <ltng:require scripts="{!$Resource.chartJS23}" afterScriptsLoaded="{!c.createPlannedchart}"/>
    <aura:attribute name="accrecId" type="String" default = "0018E00000Wg0ZLQAZ" />
    <canvas aura:id="chartCanvas" height="300" width="300"></canvas>
    
</aura:component>

and my controller:
({
    
    createPlannedchart: function(component) {
        var chartCanvas = component.find("chartCanvas").getElement();
        console.log(chartCanvas);
        var action = component.get("c.getReportPlanned");
        var getPlannedReportId = '00O8E000000HkNvUAK'; //Visit_reports_by_accounts%
        var accIdsub = '0018E000008IK3SQAW'; //an account
        var recId = component.get("v.accrecId");
        console.log('got recId = '+ recId);
        var urlPlannedreport = '/lightning/r/Report/'+getPlannedReportId+'/view?queryScope=userFolders&fv0='+accIdsub;
        //fv is filter value
    //e.g. 
    //https://virtualworlds--triggertes.lightning.force.com/lightning/r/Report/00O8E000000HkNvUAK/view?queryScope=userFolders&fv0=0018E000008IK3SQAW
    //console.log(urlPlannedreport);
       
    action.setParams({
        "AccId": recId // component.get("v.accrecId")
    });
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            var reportResultData = JSON.parse(response.getReturnValue());
            console.log(JSON.stringify(reportResultData));
            var chartData = [];
            var chartLabels = [];
            var gDown = reportResultData.groupingsDown;
            console.log('gDown = ',gDown);
            var nullcheck = reportResultData.groupingsDown.groupings;
            if (nullcheck !== null) {
                for (var i = 0; i < (reportResultData.groupingsDown.groupings.length); i++) {
                    //Iterate and prepare the list of Labels for the chart
                    var labelItem = reportResultData.groupingsDown.groupings[i].label;
                    chartLabels.push(labelItem);
                    var keyTemp = reportResultData.groupingsDown.groupings[i].key;
                    //Prepeare the chart data to be plotted.
                    var valueTemp = reportResultData.factMap[keyTemp + "!T"].aggregates[0].value;
                    chartData.push(valueTemp);
                }//next i
            }//endif nullcheck
            
            
            //Construct chart-doughnut/bar
            var chart = new Chart(chartCanvas, {
                type: 'bar',
                data: {
                labels: chartLabels,
                datasets: [{
                label: "Count",
                data: chartData,
                backgroundColor: [
                "#52BE80",
                "#76D7C4",
                "#1E8449",
                "#2ECC71",
                "#FFB74D",
                "#E67E22",
                "#F8C471",
                "#3498DB",
                "#00BCD4",
                "#D32F2F",
                "#82E0AA",
                "#AFB42B"
                ]
            }]
                                  },
                                  options: {
                                  responsive: true,
                                  title: {
                                  display: true,
                                  text: 'Planned Visits'
                                  },
                                  scales: {
                                  
                                  yAxes: [{
                                  ticks: {
                                  // max: 100,
                                  stepSize: 25,
                                  beginAtZero: true
                                  },
                                  scaleLabel: {
                                  display: true,
                                  labelString: 'Visits Count'
                                  },
                                  }],
                                  xAxes: [{
                                  scaleLabel: {
                                  display: true,
                                  labelString: 'Created Date'
                                  }
                                  }]
                                  },
                                  maintainAspectRatio: false,
                                  legend: {
                                  display: false,
                                  position: "right",
                                  fullWidth: false,
                                  }
                                  }
                                  });
                                  
                                  
            
        } else if (state === "ERROR") {
            console.log('Problem, response state: ' + state);
        }//endif error
        
        });
        $A.enqueueAction(action);
        
        
    },//createPlannedchart
})

I hope someone can't point me in the right direction.

Here's my returned metadata:
{"reportMetadata":{"topRows":null,"standardFilters":null,"standardDateFilter":{"startDate":null,"endDate":null,"durationValue":"CUSTOM","column":"DUE_DATE"},"sortBy":null,"showSubtotals":false,"showGrandTotal":false,"scope":"organization","reportType":{"type":"AccountCustomEntity$Visit_Report__c","label":"Companies with Visit Reports"},"reportFormat":"SUMMARY","reportFilters":[{"value":"0018E00000Wg0ZLQAZ","operator":"equals","filterType":"fieldValue","column":"ACCOUNT_ID"}],"reportBooleanFilter":null,"name":"Visit reports by accounts","id":"00O8E000000HkNvUAK","historicalSnapshotDates":null,"hasRecordCount":true,"hasDetailRows":false,"groupingsDown":[{"sortOrder":"ASCENDING","sortAggregate":null,"name":"ACCOUNT.NAME","dateGranularity":"NONE"}],"groupingsAcross":null,"division":null,"developerName":"Visit_reports_by_accounts","detailColumns":["CUST_NAME","Visit_Report__c.Date__c","Visit_Report__c.Type__c","Visit_Report__c.Goal_of_the_visit__c","Visit_Report__c.Goal_of_next_visit__c","Visit_Report__c.Main_competitor__c"],"description":null,"customSummaryFormula":null,"currencyCode":"GBP","crossFilters":null,"buckets":null,"aggregates":["RowCount"]},"reportExtendedMetadata":{"groupingColumnInfo":{"ACCOUNT.NAME":{"name":"ACCOUNT.NAME","label":"Account Name","groupingLevel":0,"dataType":"STRING_DATA"}},"detailColumnInfo":{"Visit_Report__c.Main_competitor__c":{"name":"Visit_Report__c.Main_competitor__c","label":"Main competitor","dataType":"PICKLIST_DATA"},"Visit_Report__c.Goal_of_next_visit__c":{"name":"Visit_Report__c.Goal_of_next_visit__c","label":"Goal of next visit","dataType":"STRING_DATA"},"Visit_Report__c.Goal_of_the_visit__c":{"name":"Visit_Report__c.Goal_of_the_visit__c","label":"Goal of the visit","dataType":"STRING_DATA"},"Visit_Report__c.Type__c":{"name":"Visit_Report__c.Type__c","label":"Type","dataType":"PICKLIST_DATA"},"Visit_Report__c.Date__c":{"name":"Visit_Report__c.Date__c","label":"Date","dataType":"DATE_DATA"},"CUST_NAME":{"name":"CUST_NAME","label":"Visit Report: Visit Report Name","dataType":"STRING_DATA"}},"aggregateColumnInfo":{"RowCount":{"name":"RowCount","label":"Record Count","downGroupingContext":null,"dataType":"INT_DATA","acrossGroupingContext":null}}},"hasDetailRows":false,"groupingsDown":{"groupings":null},"groupingsAcross":{"groupings":null},"factMap":{"T!T":{"key":"T!T","aggregates":[{"value":0,"label":"0"}]}},"allData":true}

​​​​​​​
 
I am overriding "new event" from calendar in an aura component. How do I get the date from the selected cell? It defaults to today.
I have system.debug statements at the start of and throughout my method and they all report as expected.
I create a new list of a wrapper class. .
When I add a newly created wrapper object to the list, it causes any debug statements before the call to disappear.
Any suggestions?
I can create a file using:
String strDebug = 'some debug information \n';
       
        
        //ContentDocument
        //SELECT title,  LatestPublishedVersionId FROM ContentDocument where title = 'debuglog.txt'
        ContentVersion file = new ContentVersion(
            title = 'debuglog.txt',
            versionData = Blob.valueOf( strDebug ),
            pathOnClient = '/debuglog.txt'
        );
        
        insert file;

but how do I overwrite it (add a new version) so I don't get multiple 'debuglog.txt' files?
Is there a 'Who' lookup or do I need to have both a Contact and a User field with a check that only one of these is used?
What, if any, are the pitfalls?
A Trailblazer Community posting (https://success.salesforce.com/_ui/core/userprofile/UserProfilePage?u=00530000001sMqZ&tab=sfdc.ProfilePlatformFeed&fId=0D53A00004Y1vM9&s1oid=00D300000000iTz&emkind=chatterGroupDigest&s1nid=0DB30000000072L&emtm=1566722973622&s1uid=0053A00000DGqXQ&fromEmail=1&s1ext=0)led me to develop this handy solution for exporting the Country and State codes. Knowledge article 338321  (https://help.salesforce.com/articleView?id=000338321&type=1&mode=1) was the starting point.
Here's the Visualforce Page:
<apex:page controller="ExportToExcelController" readOnly="true" 
    action="{!fetchListOfCountryCodes}" contentType="application/vnd.ms-excel#{!fileName}.xls">
  <!-- https://help.salesforce.com/articleView?id=000338321&type=1&mode=1 -->  
    
    <table>
        <apex:repeat value="{!Countries}" var="cos">
            <tr>
            <td><apex:outputText>{!cos[0]}</apex:outputText></td>
            <td><apex:outputText>{!cos[1]}</apex:outputText></td>
            </tr>
        </apex:repeat>
        <tr></tr>
        <apex:repeat value="{!States}" var="st">
            <tr>
            <td><apex:outputText>{!st[0]}</apex:outputText></td>
            <td><apex:outputText>{!st[1]}</apex:outputText></td>
            </tr>
        </apex:repeat>
        
    </table>
    
</apex:page>

and the controller:
public class ExportToExcelController {
    
    public String fileName {get; set;}
    public List<List<String>> Countries {get; set;}
    public List<List<String>> States {get; set;}

    public void fetchListOfCountryCodes() {
        
        List<Schema.PicklistEntry> ple;
        fileName = 'countryandstatecodes';
        
        Countries = new List<List<String>>();
        Schema.DescribeFieldResult fieldResult = User.Countrycode.getDescribe();
        ple = fieldResult.getPicklistValues();
        //System.debug('Picklist::'+ple);
        for( Schema.PicklistEntry f : ple){
            
            List<String> aCountry = new List<String>();
            aCountry.add(f.getLabel());
            aCountry.add(f.getValue());
            
        	//System.debug(f.getLabel() +'::'+ f.getValue());
            Countries.add(aCountry);
        }
        
        States = new List<List<String>>();
        fieldResult = User.statecode.getDescribe();
        ple = fieldResult.getPicklistValues();
        //System.debug('Picklist::'+ple);
        for( Schema.PicklistEntry f : ple){
            
            List<String> aState = new List<String>();
            aState.add(f.getLabel());
            aState.add(f.getValue());
            
        	//System.debug(f.getLabel() +'::'+ f.getValue());
            States.add(aState);
        }
        
    }//fetchListOfCountryCodes
}//ExportToExcelController

​​​​​​​
The "Search in Files" feature is particularly irritating because it doesn't search components.
Also, the debug logs won't show the last few lines without jumping back up the list.
The "Search"  box overlays the horizontal scroll bar.
I'm currently hardcoding an input value into a vf page.
When testing, I want a different value.

<!-- Normal Run-->
<apex:input value="runtime" name="status"/>
<!-- Test-->
<apex:input value="testing" name="status"/>

Does a vf page have the equivalent of the apex isTest() function?

or is there another method of forcing a different value to be used during testing?
I'm using force.com IDE Eclipse to develop apex and Lightning components.
The test results shows a list of classes/components with their code coverage.
Ideally, selecting one shows the lines of code not covered.

However, sometimes I get the message "unable to find the apex source" and a number of dialogues pop up saying that.

What is the correct procedure to resolve this?


​Any pointers greatly appreciated.
I have a custom object for territories holding postcode and manager of that area.
I want to search for a postcode/zip match and update the page with the result.
I'm using a command button to initiate the search.
My search is returning the correct result but not refreshing the other fields.
I guess I'm not using rerender correctly but can't get it to work.
Please help.

Here's the code:

<apex:page controller="TerritoryController" tabstyle="Territory__c">
    <apex:form >
        
        <apex:pageBlock title="Area Representative Lookup" id="theBlock">


            <apex:pageBlockSection columns="1" id="theSection">
                     


                
                <apex:outputText value="{!Area}"/>
                <apex:outputText value="{!Name}"/>
                <apex:outputText value="{!Manager}"/>
                <apex:outputText value="{!Postcode}"/>
                
                
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="search by postcode" for="searchText" />
                    <apex:inputText value="{!searchText}" id="SearchText"/>
                </apex:pageBlockSectionItem>
                
                
                
            </apex:pageBlockSection>

            <apex:pageBlockButtons >
                <apex:commandButton action="{!lookup}" value="Lookup"   rerender="theSection"/> 
            </apex:pageBlockButtons>
<!-- rerender="theBlock"  immediate="true" -->
        </apex:pageBlock>
        
    </apex:form>
</apex:page>

public class TerritoryController {
    // Called by apex page:
    // ...salesforce.com/apex/vwAreaRepLookup
    
    public List<Territory__c> myTerList;
    
    public string name;
    public string postcode;
    public string area;
    public string manager;
    public string searchText;
           
    
     //constructor
    public TerritoryController() {
        searchText = '';
    }



    public List<Territory__c> getmyTerList() {
        
        system.debug('in getmyTerList searchText=>'+searchText+'<');
        
        ApexPages.Message msgErr;
        ApexPages.Message msgInfo;
        String err = 'Hello';
        String info = 'Hi!';
        
//example error post
//err='whatever';
//msgErr = new ApexPages.Message(ApexPages.Severity.ERROR, err);
//ApexPages.addmessage(msgErr);

//example info post
//info = 'searchtext=>'+searchText+'<';
//msgInfo = new ApexPages.Message(ApexPages.Severity.INFO, info);
//ApexPages.addmessage(msgErr);

Territory__c[] myTerList = [Select territory__c.area__c, territory__c.postcode__c, territory__c.name, territory__c.territory_manager__c from Territory__c where postcode__c = :searchText ];
        return myTerList; 
            
            

    }//getMyRetLicList
    
    
    public String getManager() {
        return 'nothing';
    }

    public String getArea() {
        return 'nothing';
    }

    public String getName() {
        return 'nothing';
    }
    
    public String getPostcode() {
        system.debug('in get postcode');
        return 'nothing';
    }
    
    public String getSearchText() {
        return 'MK';
    }
    
    public void setSearchText(String theSearchText) {
        searchText = theSearchText;
    }
    
    public void lookup() {
        
        system.debug('in lookup searchText=>'+searchText+'<');
            
    
        Territory__c result = [Select territory__c.area__c, territory__c.postcode__c, territory__c.name, territory__c.territory_manager__c from Territory__c where postcode__c = :searchText limit 1];
        
        name = result.name;
        postcode = result.postcode__c;
        area = result.area__c;
        manager = result.territory_manager__c;
        system.debug('name: '+name);
    

    }//Lookup


}//TerritoryController
I have a page that gets criteria including current location using javascript.
I then construct a url with parameters and launch another page using apex redirect to show a map - but it doesn't draw the map.
Yet, when I launch the page directly using the constructed URL, the map appears.
When sandbox laucnches it, a complex URL is displayed.
What is happenning and how can I remedy it?
I have festooned my code with console logs and system logs but can't see why it fails.
Please help.
I struggled to create a simple Lightning Component that I could add to an account page, so thought I'd share my result.
The presentation of the information isn't tidy yet...that's my next learning excercise!
This can also be used as an action via an action button on the page.
It was based on the article
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_using_lex_s1_config_action_recordid.htm#components_using_lex_s1_config_action_recordid

Hope this helps others.

accountSummary.cmp
-----------------------------
<aura:component controller="accountSummaryController"
                implements="force:lightningQuickActionWithoutHeader,force:hasRecordId,force:appHostable,flexipage:availableForAllPageTypes">
    
    <!-- based on https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_using_lex_s1_config_action_recordid.htm#components_using_lex_s1_config_action_recordid -->

     <aura:attribute name="account" type="Account" />

    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <!-- Display details about the account -->
    <div class="slds-page-header" role="banner">
        <p class="slds-text-heading--label">{!v.account.Name}</p>
    </div>
    
    <!-- Display the details form needs work -->
    <div class="slds-form--stacked">
  
    <div class="slds-form-element">       
        <p class="slds-text-heading--label">{!v.account.BillingCity}</p>
    </div>
        <div class="slds-form-element">    
        <p class="slds-text-heading--label">{!v.account.BillingState}</p>
    </div>
    <div class="slds-form-element"> 
        <p class="slds-text-heading--label">{!v.account.Website}</p>
    </div>
 
    </div>

</aura:component>

accountSummaryController.js
---------------------------------------

({
    doInit : function(component, event, helper) {

        // Prepare the action to load account record
        var action = component.get("c.getAccount");
        action.setParams({"accountId": component.get("v.recordId")});

        // Configure response handler
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(component.isValid() && state === "SUCCESS") {
                component.set("v.account", response.getReturnValue());
            } else {
                console.log('Problem getting account, response state: ' + state);
            }
        });
        $A.enqueueAction(action);
    }   
})

...and the controller class
accountSummaryController.apxc
-------------------------------------------

public with sharing class accountSummaryController {

    @AuraEnabled
    public static Account getAccount(Id accountId) {
        // Perform isAccessible() checks here
        return [SELECT Name, BillingCity, BillingState,website FROM Account WHERE Id = :accountId];
    }
    
}
 
Could someone explain the query syntax in
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_methods.htm
which uses
results = (List<Account>)[FIND :searchText RETURNING account(Name, billingpostalcode, Phone)][0];
For a start, I don't know what the [0] is doing.
Also, what are search criteria. It isn't returning every account I'd expect.

An alternative would be:
        results = [SELECT  Name, Phone, billingpostalcode FROM Account where name like :searchText];
although I'd add a '%' to the search text.

Hope someone can explain.
Thanks.
 
I've been trying to add the attendees as a related list on my custom controlled apex page but can't find a syntax that works.
I get errors like: "'EventRelations' is not a valid child relationship name for entity Event "

<apex:relatedList subject="{!anEvent}" list="EventRelations">
        <apex:facet name="header">Attendees</apex:facet>
    </apex:relatedList>

where "anEvent" is my event record (public Event in controller) which succesfully returns all the fields of the event in a pageBlock.

​Any ideas?
I'm trying to "Build a mapping application for iPhone" following the instructions at
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_mobile_example.htm
but, as far as I'm concerned, there are some missing instructions.
I'm new to this so, although it may seem obvious, I just don't know how to make it work.

There are two parts that don't make sense to me and I'd be grateful for any assistance.

I'm not sure what to do with the
"The following markup defines the iuivf page used as the template:"
Where do I save the code and as what?

Similarly, what do I do with
" Visualforce page that displays the phone number and rating of the account the user selected from the list view."
What do I call it? Is this the main page that is called to make this work?

Many thanks, Dave.

 
I'm having great difficulty assigning and testing account ids that I've created in a custom object.

I want to compare accounts
if (thisAc == thatAc){
} //endif

and tried
if (thisAc.id == thatAc.id){
​} //endif

My custom object has an account field: MyCustomObject__c has referenceCompany__c
I can't seem to copy it to another custom object - even a temporary Account

starting from MyCustomObject my1...

MyOtherCustomObject myOco = new(MyOtherCustomObject);
myOco.copiedCompany__c = my1.referenceCompany__c;

I've tried:
Account thisAc = .my1.referenceCompany__c;
and
Account thatAc= .my1.referenceCompany__r; (which seems close to the answer).


Any suggestions?

Thanks in advance.


 
I am trying to achieve the following:
 
I have accounts:
ManufacturerA
RetailerX
RetailerY
 
There is a custom object “Licence” consisting of:
Licence holder (an account e.g. RetailerY) with other licence details.
An account may have multiple licences.
 
I have a custom object “Retailer of” consisting of:
Manufacturer (account)
Retailer (account)
For example;
RetailerX is a retailer of ManufacturerA
RetailerY is a retailer of ManufacturerA
 
I want to report the licence data of retailers of a manufacturer.
 
Manufacturer: ManufacturerA:
               Retailer: RetailerX
                              Licence 001 …other details
   Licence 005 …other details
               Retailer: RetailerY
                              Licence 8097 …other details
                              Licence 8098 …other details
                              Licence 8099 …other details
                              Licence 8100 …other details


I have tried joined reports but haven't found a way to achieve it.
Please can anyone tell me how?
(I'm assuming I have structured the data in the only way possible using custom objects).

Does it require a VisualForce page?

Any suggestions and examples would be much appreciated.

Dave.
 
The following code throws an exeption at the callout request
CALLOUT_REQUEST [35]|System.HttpRequest[Endpoint=http//:www.virtualworlds.co.uk/getParams.php, Method=POST]
and genearates the error,
"no protocol: http//:www.virtualworlds.co.uk/getParams.php".

I generate the list from custom objects and have verified that the list has entries.

Can you tell me what is wrong?

Code:

public class HelloWorld {
    
    public static void tryPost() {

     System.debug( 'Posting...' );
        List<licence__c> myList = new List<licence__c>();
        myList= [select Id,Name from licence__c LIMIT 20];  
        
      
        String endPoint = 'http//:www.virtualworlds.co.uk/getParams.php';
        String method = 'POST';
        
        //Prepare http req
        System.debug( 'New Request...' );
        HttpRequest req = new HttpRequest();
        System.debug( 'Set endpoint...' );
        req.setEndpoint(endPoint); 
    
        req.setMethod(method);
        String JSONString = JSON.serialize(myList);  
        req.setBody(JSONString);
        System.debug( 'new Http...' );
        Http http = new Http();
        System.debug( 'Send request...' );
        HTTPResponse res = http.send(req);
        System.debug( 'Result?...' );
        System.debug(res.getBody());      
  

}
The "Search in Files" feature is particularly irritating because it doesn't search components.
Also, the debug logs won't show the last few lines without jumping back up the list.
The "Search"  box overlays the horizontal scroll bar.
Hello,

I have a usecase wher user do some actions on page and some screen changes happens.
Is some cases, the users cancel the screen and redos few step.

I see that when parameter is count=1 all is working fine but when its count=2 or count=3, it fails, 

what can be real issue and what steps can i take to solve it 
https://sandoxurl/lightning/lightning/o/Case/new?recordTypeId=012XXXXG&count=1
Thank you for suggestion
Hello all,

We have orders with associated accounts being created as part of an integration with eCommerce and ERP.

It is essentially creating person accounts since these are consumers. Instead of enabling person accounts, I would like to create a new contact record using the data from the account where Account.Person__c = true (custom field created to designate consumer accounts). 

This would be an easy PB but I'm having trouble setting values with the name fields. Any shared experience on how to "reverse-concatenate" Account.Name into Contact first name & last name?

Thanks in advance
  • January 05, 2021
  • Like
  • 0
How do yo navigate to the Calendar tab or to the Event list in Salesforce Mobile? Do we use the force:navigateToComponent? or lightning:navigation?  Any example is greatly appreciated.
What I have:
An accountId: '001R0000005Xk58IAC'

What I want to get:
1. Events based on the accountId.
Query I have: 
SELECT id FROM Event where AccountId = '001R0000005Xk58IAC'

2. EmailMessage based on the accountId (it's called relatedToId in emailMessage object).
Query I have: 
SELECT id FROM EmailMessage where relatedToId = '001R0000005Xk58IAC'


My question is, how can I use ONE query to get both of them?
Are there something like:
SELECT (Event.id, EmailMessage.id) from (Event, EmailMessage) where event.accountId = '001R0000005Xk58IAC' AND emailmessage.id = '001R0000005Xk58IAC'

By the way, I just need to get the number of the returned results, which means I just need to know the event.count + emailMessage.count, but I want to get them in one query.

Thanks.
 
All examples that I have seen so far show how to add a custom button/action on Leads List View. I am looking for a way to launch a flow from a custom buttom/action from Account List View.

The Flow is to create account and related contact records and it needs to happen only through a flow, as the customer wants point and click customization.

User-added image

So far, I have only been able to launch the flow from within a record- by adding the action on the account page layout. However, my requirement is to launch the flow from the Account List View itself and not requiring the user to first have to select any other record. I have also tried creating a VF page to launch the flow from.


The issue that I am running into is

1- I do NOT see 'List View' as an option when I navigate to 'Search Layouts' on the Account Object and the 'Default Layout' does not have the custom button that I created

User-added image

Default Layout- supports only buttons that create or update a record

User-added image

2- I do see 'List View' listed when I navigate TO 'Search Layouts for Salesforce Classic' on the Account Object, however, the button to launch flow still does not show up under custom buttons and the only buttons that show up are related to either creating/updating a record. Also, I am sure if seeing the button to launch a flow under Search Layouts for Salesforce Classic would do me any good as I am working in Lightning
User-added image
User-added image


Direction on how to proceed ahead is greatly appreciated. Thank you in advance!
As of Spring 20 release, we can again prepopulate field values using a URL - aka URL hacking (see release note here (https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_general_lex_navigate_to_record_dfv.htm)).

I, for one, am so happy for this feature. However, there is one minor problem. When the URL is invoked, the new record modal pops up, and if the user chooses to Cancel, a blank page is displayed instead of returning to the page where the URL was called.

Below is the URL that I'm using. It is invoked with a custom list button located in a related list of an Opportunity.

/lightning/o/Case/new?defaultFieldValues=
AccountId={!Opportunity.AccountId},
Opportunity__c={!Opportunity.Id}

I've tried including a retunURL parameter - in different places in the URL. But no luck.
Hello community,

We are experiencing an issue with a Lightning Component since the Spring 20 release.
This LC component contains a lightning:datatable on which we can perform actions on a specific row.
For that, on the controller side we use (as specified in official documentation) event.getParam('row'); to retrieve the selected row.
To make sure the issue is not related to my actual code, I recreated a very basic Lighning app with a LC that contains a ligthning:datatable.

When I launch an action from first row, I get "rowIndex is -1" instead of "rowIndex is 0".
When I launch an action from second row, I get "rowIndex is -1" instead of "rowIndex is 1".

To make sure the issue is related to Spring 20, I deployed this Lightning app to our Production org which is still in Winter 20 and I get successful results :
When I launch an action from first row, I get "rowIndex is 0" as expected
When I launch an action from second row, I get "rowIndex is 1" as expected

So I really believe this is a bug related to Spring 20 as we did not change our code at all and it was working perfectly in Winter 20 release.

I am wondering if anybody is expecting the same issue as us, and most importantly if anybody has a workaround for this.

Thanks

Temp.app
<aura:application extends="force:slds">
     <c:Temp_Test />
   </aura:application>

Temp_Test.cmp
 
<aura:component >
<aura:attribute name="mydata" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.init }"/>

<div class="slds-grid slds-grid_align-center">
    <lightning:layout verticalAlign="start" multipleRows="true" class="slds-box slds-size_4-of-4">


        <lightning:datatable data="{! v.mydata }"
            columns="{! v.mycolumns }"
            keyField="id"
            onrowaction="{! c.getSelectedRow }"/>


    </lightning:layout>
</div>
</aura:component>
Temp_TestController
({
init: function (cmp, event, helper) {
    var actions = [
        { label: 'Show details', name: 'show_details' }
    ];
    cmp.set('v.mycolumns', [
        { label: 'Opportunity', fieldName: 'opportunityName', type: 'text'},
        { label: 'Phone', fieldName: 'phone', type: 'phone'},
        { type: 'action', typeAttributes: { rowActions: actions } }
    ]);

        cmp.set('v.mydata', [{
                opportunityName: 'Cloudhub',
                phone: '2352235235'
            },
            {
                opportunityName: 'Quip',
                phone: '2352235235'
        }]);
},
getSelectedRow: function (cmp, event) {
    var row = event.getParam('row');
    var rows = cmp.get('v.mydata');
    var rowIndex = rows.indexOf(row);
    alert("Row index is : " + rowIndex);
}
 })

Screenshot :

User-added image



 
I am using <lightning:inputField /> for creating input field in component,I want make input is required or mandatory in lightning component.

Please provide sample code or solution around above senario.

I have a working dynamic picklist, but I want it to select multiple options. Help me to do it, please..
    
Here's me code:

Lightning Component

<aura:attribute name="options" type="String[]" description="options" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="newOpp" type="Opportunity" default="{'sobjectype': 'Opportunity',
                                                           'Name': '',
                                                           'CloseDate': '',
                                                           'Amount': '',
                                                           'StageName': '',
                                                           'Donate_to__c': ''}"/>
															  
<lightning:combobox aura:id="MultiSelect"
							label="Donate to"
							placeholder="Select 1 or more options"
							value="{!v.newOpp.Donate_to__c}"
							required="true"
							messageWhenValueMissing="Hey! Don't forget me!"/>

JavaScript Controller

doInit : function(component, event, helper) {
        var action = component.get("c.getDonateTo");
        var input = component.find("MultiSelect");
        var opts=[];
        
        action.setCallback(this, function(a) {
            for(var i=0;i< a.getReturnValue().length;i++){
                opts.push({"class": "optionClass", label: a.getReturnValue()[i], value: a.getReturnValue()[i]});
            }
            input.set("v.options", opts);
            
        });
        $A.enqueueAction(action);
		
},
Controller class
@AuraEnabled        
public static List<String> getDonateTo(){
  List<String> options = new List<String>();
  Schema.DescribeFieldResult fieldResult = Opportunity.Donate_to__c.getDescribe();
  List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
      for (Schema.PicklistEntry f: ple) {
            options.add(f.getLabel());
      }
      return options;
}
It appears that 'most' of the options available for customizing page layout, only affects the 'edit' page layout and not the 'new' record page layout.
I am looking at customizing page layout while creating 'new' record.

I want to have some field as 'read only' and some fields not visible in new record page layout (just like formula field)
a. Do I have to go with creating new VF page?
b. Is there any other way in Salesforce?

Need Help
Hi,
Can anyone review the codes quickly and check why the component is not showing on the list of available components on the lightning app builder although it has force:appHostable? Thanks!

COMPONENT
<aura:component controller="NonUserAccountTeamController" 
implements="force:appHostable,force:hasRecordId,flexipage:availableForAllPageTypes">

	<aura:attribute name="nonUserAccountTeamMembers" type="Non_User_Account_Team__c[]" />
	<aura:attribute name="employees" type="Employee__c[]" />
	
	<aura:handler name="updateNonUserAccountTeam" event="c:updateNonUserAccountTeamUser"
        action="{!c.handleUpdateNonUserAccountTeam}"/>
			
	<aura:handler name="init" action="{!c.doInit}" value="{!this}" />
    
    <div class="slds">
 
      <div class="slds-page-header">
        <div class="slds-grid">
          <div class="slds-col slds-has-flexi-truncate">
            <p class="slds-text-heading--label">Coverage Team</p>
              <div class="slds-grid">
                <div class="slds-grid slds-type-focus slds-no-space">
                  <h1 class="slds-text-heading--medium slds-truncate" title="Coverage Team">
                  {!'Coverage Team Members ' + '(' + 'Non_User_Account_Team__c[].size' +')'}
                  </h1>
                </div>
                <ui:button aura:id="button" buttonTitle="Manage the employees handling this account" 
                class="button" label="Add Coverage Team Members" press="{!c.clickAdd}"/>
              </div>
           </div>
         </div>
       </div> <!-- End of Header -->
		</div> <!-- End of SLDS -->
    <c:NonUserAccountTeamListItem nonUserAccountTeams="nonUserAccountTeamMembers" employees="employees"/>
    
    <ui:button aura:id="button" buttonTitle="View all the members of this team" 
    class="button" label="View All" press="{!c.clickViewAll}"/>
     

	
</aura:component>

CONTROLLER: 
({
	doInit : function(component, event, helper) {
		// Prepare the action to load account record
		var action = component.get("c.getUsers");
		action.setParams({
			"recordId" : component.get("v.recordId")
		});
		// Configure response handler
		action.setCallback(this, function(response) {
			var state = response.getState();
			if(component.isValid() && state === "SUCCESS") {
				component.set("v.nonUserAccountTeamMembers", response.getReturnValue());
			} else {
				console.log('Problem getting account, response state: ' + state);
			}
		});
		$A.enqueueAction(action);
	},
	
	clickAdd : function (component, event, helper) {
	    var createRecordEvent = $A.get("e.force:createRecord");
	    createRecordEvent.setParams({
	        "entityApiName": "Non_User_Account_Team__c"
	    });
	    createRecordEvent.fire();
	},
	
	clickViewAll : function (component, event, helper) {
	    var relatedListEvent = $A.get("e.force:navigateToRelatedList");
	    relatedListEvent.setParams({
	        "relatedListId": "nonUserAccountTeamMembers",
	        "parentRecordId": component.get("v.recordId")
	    });
	    relatedListEvent.fire();
	},
	
	handleUpdateNonAccountUserTeam: function(component, event, helper) {
		//Update the new expense
		var updatedUser = event.getParam("nonUserAccountTeamMember");
		helper.updateUser(component, updatedUser);
	},
	
})

HELPER:
({
	saveUser: function(component, user, callback) {
	    var action = component.get("c.saveUser");
	    action.setParams({
	        "user": user
	    });
	    if (callback) {
	        action.setCallback(this, callback);
	    }
	    $A.enqueueAction(action);
	},

	
	createUser: function(component, user) {
	    this.saveExpense(component, user, function(response){
	        var state = response.getState();
	        if (component.isValid() && state === "SUCCESS") {
	            var users = component.get("v.nonUserAccountTeamMembers");
	            expenses.push(response.getReturnValue());
	            component.set("v.nonUserAccountTeamMembers", users);
	        }
	    }); 
	},
	
	updateUser: function(component, user) {
	    this.saveExpense(component, user);
	},
	
})

 
I am getting this error: The number of results does not match the number of interviews that were executed in a single bulk execution request.
Here is the apex class I am using, I want to store list<string> data from a json file into a flow variable:
global class par{

    global static List<string> l = new list<string>();
    
@InvocableMethod(label='Get Map' description='Returns the values of Maps')
    global static List<String> CallMap(){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyBOyIQi54LMykmzSOvCuQ2naVvVQEsEfHw');
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
        while (parser.nextToken()!= null)
        {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME))
            {
                    string fieldName = parser.getText();
                    parser.nextToken();
                if(fieldName == 'place_id')
                {
                    string place = parser.getText();
                    system.debug(place);
                    l.add(place);
                	parser.nextToken();
                }else if(fieldName == 'status')
                	{
                    string status = parser.getText();
                    system.debug(status);
                    l.add(status);
                    }
        	}
    	}
        return l;
    }
}



 

 

Hi there,

 

I am getting the following ERROR:

Exception: System.JSONException: Illegal value for primitive

When I try to deserialize the HTTP response from Jive to an object.

 

JivePersonObject personRecord = (JivePersonObject) System.JSON.deserialize(jiveResponse, JivePersonObject.class);

 

I have validated the JSON string at http://jsonlint.com/ and it is valid. 

 

This is not happening for all the response. It is happening for some response and some of them don't have the issue.

 

I was wondering if anyone have come across this issue before. Not sure what I am doing wrong here. Thanks.

 

Sanch

I want to use record Type to limit trigger action. 

 

Now I use querey to get it my code liks below

string Id = [SELECT id from RecordType where Name ='Someone'].Id;

 

I also found this page, we could use method to get the Record Type Id to avoid the query.

I still can't understand it.

 

Is there some simple and easy wayt to get the ID only by Record Type's Name?

Hi folks,

 

Is there any way I can convert the body of an inbound email from html to Plain Text? I've set up a service to email directly into chatter, but html emails sent from my organisation into Chatter are all of over 1,000 characters in length (even if I send a blank email). So, I'm looking for a way to strip the body text from the emails and discard all the html "nonsense", rather than force users to send emails in Plain Text format, which they'll be disinclined to do.

 

Any help anyone can give would be massively appreciated.

 

Thanks,

Lee

Hi,

   First, i added some values to the List, and then I return the entire list to visualforce page, my problem is that i can not show specific value of element in the visualforce page but only can show all the elements together once. Anybody has this experience, welcome.

 

I know this is probably a silly question but I'm new to web programming and salesforce/apex/vf and I need to do this but cannot find a way.

 

I need to be able to simply print today's date on a page.  I've tried embedding some javascript in <script></script> tags and that does not seem to do anything at all.

 

Thank's to all that read 

  • February 20, 2009
  • Like
  • 0
Hello all !!

I have to do a find and replace a string on a variable (string). I know there is a matcher object but I couldnt find much documentation on the usage. Any one else used this object ? or is there any other simple function to get this done. Pls help

Thanks
Raghu


Message Edited by Raghu_dev on 05-14-2008 05:45 PM
I want to displqy events field on email template. so plz help me or suggest what can i do to print any of field may be standard or custom in email template

I use a controller to display a list of products with a checkbox against each product value . When the end user selects few products and clicks "add quantity" button it should navigate to another VF page in which i should display the selected products and an input filed for quantity. Quite similiar to the way of adding products in opportunity. In the code below im using a single controller for 2 VF pages. Problem i m facing here is when the second page is called the wrapperList becomes null instead of holding the values of the selected products. Please give me some suggestions.

 

public with sharing class productAdd
{        
    public  List<Product2> Stdproduct{get;set;}
    public List<wrapper> wrapperList {get;set;}  
    public list<wrapper> SelectedprodList{get;set;}	
    public class wrapper
    {
        public product2 cont{get;set;}
        public Boolean selected{get;set;}
        public integer quantity{get;set;}
        public wrapper(product2 c)
        {
            cont = c;
            selected = false;
        } 
    }
	public  List<wrapper> getProdList()
    {        
        if((wrapperList == null) || (wrapperList.size() == 0))
        {                      
            wrapperList = new List<wrapper>();
            Stdproduct = [Select id, Name from product2 limit 2];           
            for(Product2 c :(List<Product2>)Stdproduct)            
            {               
                wrapperList.add(new wrapper(c));
            }
        }             
        return wrapperList;
    }
    
    public PageReference AddQuantity()
    {   
        PageReference pageRef= new PageReference('/apex/AddQuantity');
        pageRef.setredirect(true);        
        return pageRef;           
    }

    public list<wrapper> getSelectedproducts()
    {
        selectedprodList = new list<wrapper>();      
        for(wrapper cCon:getProdList())
        {            
            if(cCon.selected==true)  
            {                        
                selectedprodList.add(cCon);
            }                           
        }        
        return selectedprodList;           
    }        
}

<!-- 1st Page -->
<apex:page Controller="productAdd" sidebar="false">
    <table  width="90%">
	    <apex:form>
			<apex:repeat value="{!ProdList}" var="l" >               
				<tr>
				<td>
				<apex:inputCheckbox value="{!l.selected}"/>
				</td>
				<td class="fieldname">{!l.cont.name}</td>                       
				</tr>                
			</apex:repeat>
				<tr>
				<apex:commandButton value="Add Quantity" action="{!AddQuantity}"/>
				</tr>             
	    </apex:form> 
    </table>
</apex:page>


<!-- 2nd Page -->
<apex:page Controller="productAdd">
	<apex:form >
		<apex:pageBlock > 
			<apex:pageBlockTable value="{!Selectedproducts}" var="c" id="table"> 
				<apex:column value="{!c.cont.Name}" />                
				<apex:column >
				<apex:inputText value="{!c.quantity}"/>
				</apex:column> 
			</apex:pageBlockTable> 
		</apex:pageBlock> 
	</apex:form> 
</apex:page>