• bretondev
  • NEWBIE
  • 439 Points
  • Member since 2018

  • Chatter
    Feed
  • 7
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 30
    Questions
  • 93
    Replies
Im maping as map<invoice__c,List<line_item__c>> Now I have to calculate for each invoice sum of quantity(in line item) is greater than 100 ? if its greater then i have to update status in invoice .
I would like to create a trigger which can insert a quote and a quotelineitem when I clone an opportunity with its product. I tried many Trigger.
If someone can help me understand the problem it would be awesome! I spent already a few days on it...

trigger FacturationCreator on Opportunity (after insert, after update) {
for (Opportunity o : Trigger.new) {
if (o.Type == 'Event') {

//Opportunity oppId=[select id from Opportunity where id=:q.OpportunityId];
List<OpportunityLineItem> opplines=[select id, quantity, PriceBookEntry.Product2Id, UnitPrice, PricebookentryId
from OpportunityLineItem where OpportunityId=:o.id];
 for(OpportunityLineItem oppline:opplines){ 
List <Quote> factList = new List<Quote>();

Quote q = new Quote();
q.name = 'Quote-' + o.name;
q.Montant_1_re_ch_ance__c = 1000;
q.Date_de_Facture__c = o.CloseDate;
q.Date_1_re_ch_ance__c = o.CloseDate;
q.opportunityId = o.id;
factList.add(q);
insert q;


List<Quote> qList=[select id from Quote where opportunityId=:o.id];
for(Quote q:qList){ 
QuoteLineItem qli = new QuoteLineItem();
qli.quoteId = q.Id;
qli.UnitPrice = oppline.UnitPrice;
qli.Product2Id = oppline.PriceBookEntry.Product2Id;
qli.Quantity = oppline.Quantity;
qli.PriceBookentryid = oppline.PriceBookentryId;
insert qli;}

}
        }
    }
}
This is more of a general question but I was wondering what everyone did to improve their Apex skills?

I've done Trailheads and looked online at code usage and still struggle alot.
here should I look to learn about Apex Syntax, usage and best software/pluggins to use.
Any good books or online guides that take me through A-Z.
How Apex can be used and basic must know Apex knowledge. 😊

Thankyou
I have a forumula field that currenlty works perfectly; however, I need to add to it and I'm not sure how.
I am using it in a bid scorecard or Go/NoGo process. Each question answered contributes to the final score and determines if it is a Go or NoGo. For this, is works perfectly. I'm using the formula:
IF ( Total_Points__c >0.85,IMAGE ("/servlet/servlet.FileDownload?file=0150y000002wOqE", "Green"), 
IF ( Total_Points__c >0.80,IMAGE ("/servlet/servlet.FileDownload?file=0150y000002wOq9", "Yellow"), 
IMAGE ("/servlet/servlet.FileDownload?file=0150y000002wOq4", "Red")))
For Example....
User-added image

However, it doesn't account for when the scorecard is incomplete or isn't completely filled out. For that, I've created another pic that shows "Incomplete".

If the formula shown above is based on scores, can I insert into the formula something that states that if any of the questions aren't filled out, then the "Go/NoGo Based on Bid Status %" would show the new "Incomplete" pic?
I am working on Admin Beginner Lightning Experience Customization Set Up Your Org module (https://trailhead.salesforce.com/trails/force_com_admin_beginner/modules/lex_customization/units/lex_customization_custom_objects?trailmix_creator_id=00550000006yDdKAAU&trailmix_id=prepare-for-your-salesforce-administrator-credential) and have completed all the steps to create the objects and when clicking on the "check challenge" button, it returns the error: "Challenge Not yet complete... here's what's wrong: Could not find the 'Audit_Notes__c' field on the custom object named 'Energy_Audit__c'."
Screenshot of verification error in Trailhead for Set Up Your Org module

I have gone back into the Trailhead Playground that I used and verified that the field does exist and is related and on the custom object as I had set it up.
Energy Audit Object screenshot
Screenshot of Audit Notes related field

I can't get past this challenge and it won't complete this module unless it is verified. Is anyone else running into this?  I have successfully had all the previous challenges completed and this is the first time I got an error that I can't figure out what is missing.

Thanks in advance for your help.
Angela
Working on this in Trailhead. Get error message:
Picture of error message
My filter logic is set to the filter logic it is supposed to be set to. I tried changing the spacing and if I take out any spaces I get an error in the filter logic. Has anyone else had this problem? Or is there something really incorrect?
Screenshot of filter logic

 
I am seeing this error...'Challange Not yet complete...here's what's wrong: The 'Shift Hours' field on the 'Volunteer Shift' record is not working as expected. I'm stuck as to what I am doing wrong. It's probably a simple fix that I'm over looking. Help solving this problem would be greatly appreciated! Thanks!

User-added image
User-added image
User-added image
Hello Community

Since a few days, half of our Apex Test Classes fail in our Sandbox environment.
The strange thing is that we did not do any modifications on these classes.

The error message we get is :
"System.DmlException: Update failed. First exception on row 0 with id 0QL6E0000002O2MWAU; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): QuoteLineItem, original object: S2XUserMap: []"

Note 1:
We have found an issue on the Salesforce Known Issues website, but it dates from Winter 18 :
https://success.salesforce.com/issues_view?id=a1p3A0000008gVyQAI

Note 2 :
We only get the failures when we run the tests from the Developer Console.
When we push a Change Set to the sandbox and validate it by running Local Tests, all the tests succeed.

Note 3:
We have the same Test Classes in another Sandbox and our Production environment, and here all tests succeed.

Note 4:
We haven't touched some of those test classes for more than a year.

Note 5:
We don't know where that "S2XUserMap" object comes from.
We have never seen it in the past.

User-added image
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



 
We have a Custom Object in Pardot.
We have data that corrsponds to that Custom Object in an external system.
We want to update the Custom Object in Pardot from what is in the external Source.

I didn't find any API in Pardot that offers this feature.

Any clues?

Thanks
We want to use Salesforce DX. For this we need to enable DevHub. We can see the DevHub option in Production, but we cannot see it in our Sandboxes. Please help.
Hello

We want to know in which environment we are when running Apex, more precisely we need to know if we are in Production, or Sandbox A, or Sandbox B, etc..

At the moment, we are looking at Org Id to determine the environment, like this :
 
public static Boolean IsProductionOrg() { // Method to check of environement is Production ORG or not
        return UserInfo.getOrganizationId() == '00ecqzecqc1IkdlUAC' ? true : false; 
    }
    
        /**
     * This method retun whether this org is a production or a sandbox
     * @return true/false
     */
    public static Boolean IsPProdOrg() { // Method to check of environement is PPROD Sandbox or not
       return UserInfo.getOrganizationId() == 'cdscddscdsccsdc'  ? true : false; 
    }

We do not like this method because everytime we refresh the Sandbox, the Org IDs of the Sandboxes change and we have to update the code.

I have found this link :
http://salesforceworld4u.blogspot.com/2015/12/how-to-get-sandbox-name-in-apex.html

It says we can look at the suffix of the logged-in user, then we can find out if it is Sandbox or Production.
For example, if logged-in user is john.smith@mycompany.com.pprod , than means environment is pprod Sandbox.

We also do not like this method because we are afraid users can change their username and remove the suffix, so method will not work anymore.

What is the clean way of doing this?


 
Hello

I want to use force:recordData to load record infos, but currently it returns null.
 
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId" access="global" controller="AP_Constants">
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <aura:attribute name="recordId" type="Id" />
    <aura:attribute name="accountRecord" type="Object"/>

    <force:recordData aura:id="recordLoader"
                      layoutType="FULL"
                      recordId="{!v.recordId}"
                      targetFields="{!v.accountRecord}"
    />
    

</aura:component>
({
    doInit : function(component, event, helper) {
		
        var recid = component.get("v.recordId");
        var record = component.get("v.accountRecord");
       
})
Here when I debug var record = component.get("v.accountRecord");
record is null.
 
Hello

Is it possible to get current org Id from Lightning Component controller?

I have tried that but i get undefined value :
var orgId = $A.get("$Organization.Id");
Hello

We are using STate and Country piclists.
So on Contracts we have a ShippingAddress field that contains a ShippingCountry.

When I visualise a Swiss contract in our Salesforce UI, the ShippingCountry displays as "Suisse" ("Switzerland" in French).
Whiwh is normal because my personal language setting is set to French.

The issue is that when I query this contract with SOQL, the value of ShippingCountry is in English (Switzerland).

How can I get this ShippinCountry value in French when I query with SOQL?

I checked our company-wide settings, default language is also French.

Thanks
 
Contract c = [Select id , shippingcountry from contract where id = '8000Y000000FgEJQA0'];

system.debug('### MAB ' + c.ShippingCountry);

 
Hello

Trying to deploy a validation rukle from one sandbox to another with Workbench.
It is the first time I try, my manager has shown me how to do it the last week, now he is out of the office so I am trying by myself.
I think I am close to the right way but Cannot figure out what is missing.

He showed me that there was two steps : retrieve and deploy.

For the retrieve part I need to provide a package.xml specifying what components I want to retrieve.

So I created the following package.xml file :
 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
	<types>
		<members>VerifySiret</members>
		<name>ValidationRule</name>
	</types>
	
	<version>43.0</version>
</Package>

But when I go to Migration > Retrieve and provide my file I get this message, validation rule cannot be found :

User-added image

Can someone please explain what I am doing wrong?
Hello

I have a lightning:datatable that is fully working, however my management is asking for a slight change, but I cannot find how to do this in the documentation.

For each row of the table, there is a Details button available but first the users must click on the  Down arrow next to it.
This Details button call a JS method in the controller, and the JS method is able to see which row was clicked.

See screenshot :

User-added image
My management wants a simple link instead of the Details button.
Of course this link should be able to call the same JS method, and the JS method should be able to see which row was clicked.

Is that possible?

Here is my code currently :
 
<lightning:datatable data="{!v.searchResults}" columns="{!v.resultColumns}"  keyField="siret" hideCheckboxColumn="true" onrowaction="{!c.seeDetails}" />
init: function (component, event, helper) {
        //This method is called on initialization
        //It formats the lightning:dataTable that will display the results with the appropriate columns and data types
        
         var actions = [
            { label: 'Détails', name: 'show_details' },
        ];
        
        component.set('v.resultColumns', [
             		{label: 'Provenance', 						fieldName: 'provenanceAsIcon', 		    				cellAttributes: { iconName: { fieldName: 'provenanceAsIconName' }, iconLabel: { fieldName: 'provenanceAsIconLabel' } }},
             		{label: 'Siret', 							fieldName: 'siret', 					type: 'text'},
            		{label: 'Nom du Compte / Raison Sociale', 	fieldName: 'nomCompteRaisonSociale', 	type: 'text'},
                    {label: 'Adresse', 							fieldName: 'adresse', 					type: 'text'},
            		{label: 'CP', 								fieldName: 'cp', 						type: 'text'},
            		{label: 'Ville', 							fieldName: 'ville', 					type: 'text'},
            		{ type: 'action', typeAttributes: { rowActions: actions } }
                ]);
    }
seeDetails: function (cmp, event, helper) {
        //This method is called when the user clicks on "Voir les détails" at the row-level of the results
        //First it checks if the row that was clicked is a SF or CS record
        
        //Retrieving the provenance (SF or CS) and recordId of the row that was clicked
        var row = event.getParam('row');
        var rows = cmp.get('v.searchResults');
        var rowIndex = rows.indexOf(row);
        var provenance = rows[rowIndex]['provenance'];
        var recordId = rows[rowIndex]['recordId'];

	//More processing...


 
Hello

I am having an issue with force:createRecord event to create a new record.
When I invoke this function, the record must be created with a date field called DateMAJCreditsafe__c with today's date by default.

When I click on the button that triggers force:createRecord, I land on Account creation page, and my field is set to today's date, as expected :
User-added image

But when I save the record, the field is empty :(

User-added image

I don't understand what I am doing wrong.

This is the call to force:createRecord :
 
var createRecordEvent = $A.get("e.force:createRecord");
                    createRecordEvent.setParams({
                        "entityApiName": "Account",
                        "defaultFieldValues": {
                            'Name' : name,
                            //set some other fields
                            'DateMAJCreditsafe__c' : new Date()
                        }
                    });
                    createRecordEvent.fire();


 
Hello

I have a Custom Button that triggers displaying of a Lightning Component.
In the Custom Button, I can specify height but not width of the component.

User-added image

Currently, the width of the Lightning Component takes 50% of the screen but I want 90%.

How can I achieve that?
Hello

I have a schedulable class that implements Schedulable interface and conatins execute() method.
Now I have created Test Class but I do not manage to reach execute() method from the test class.
I have a lot of code in execute() that needs to get covered by tests.

I have seen lots of posts and official documentation, but none of the examples reach the execute method.

For example, from the official documentation :
 
@istest
class TestClass {

   static testmethod void test() {
   Test.startTest();

      Account a = new Account();
      a.Name = 'testScheduledApexFromTestMethod';
      insert a;

      // Schedule the test job

      String jobId = System.schedule('testBasicScheduledApex',
      TestScheduledApexFromTestMethod.CRON_EXP, 
         new TestScheduledApexFromTestMethod());

      // Get the information from the CronTrigger API object
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, 
         NextFireTime
         FROM CronTrigger WHERE id = :jobId];

      // Verify the expressions are the same
      System.assertEquals(TestScheduledApexFromTestMethod.CRON_EXP, 
         ct.CronExpression);

      // Verify the job has not run
      System.assertEquals(0, ct.TimesTriggered);

      // Verify the next time the job will run
      System.assertEquals('2022-09-03 00:00:00', 
         String.valueOf(ct.NextFireTime));
      System.assertNotEquals('testScheduledApexFromTestMethodUpdated',
         [SELECT id, name FROM account WHERE id = :a.id].name);

   Test.stopTest();

   System.assertEquals('testScheduledApexFromTestMethodUpdated',
   [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);

   }
}

It works but it is not sufficient in my case, beacuse it only asserts that the job is in the Scheduled Jobs queue.
It actually does not trigger the execute() method.

Please how can I reach execute() ?

 
Hello
We have two Sandboxes : one Full and one Developer sandbox.

For the Full sandbox, when we run the tests, we get test coverage but also when we click on a particular class we can see which lines are covered and which are not, thanks to the red and blue highlighting.

For the Developer sandbox, when we run the tests, we get test coverage but no red and blue highlighting.
So for example, when we have 90% coverage for a class, we cannot see which lines are affected by the the 10% missing coverage.

We've had this issue since the beginning, and it's becoming very annoying, because we have to deploy to Full sandbox to see which lines are covered.
We want to be able to do that at the beginning of our development lifecyle, that is, in the Developer sandbox.

So the question is, has anybody been able to see which lines are covered by tests in a Developer sandbox?
I have a Lightning Component which displays a <table> element after rendering.
I want to access the table and add a class to it, but for some reason it does not find the table.
Please help.
 
<aura:handler name="render" value="{!this}" action="{!c.onRender}"/>
onRender: function (component, event, helper) {
        var table = document.getElementsByTagName("table");
        if (table != undefined) {
            table.classList.add("slds-p-bottom_large");
        }
    }
getElementsByTagName does not find the table, why?

 
Hello ,

I have a ligthning:dataTable not displaying correctly.

There is no header visible and also data is not visible.
Please explain why.
 
<aura:if isTrue="{!v.showCsResults}">          	
            <lightning:datatable data="{!v.csResults}" columns="{!v.csResultsColumns}" keyField="siret" hideCheckboxColumn="true" onrowaction="{!c.siretiser}" />
        </aura:if>
 
init: function (component, event, helper) {
        //This method is called on initialization
        //It formats the lightning:dataTable that will display the CS results with the appropriate columns and data types
        
         var actions = [
            { label: 'Sirétiser', name: 'siretiser' },
        ];
        
        component.set('v.csResultsColumns', [
             		{label: 'Siret', 							fieldName: 'siret', 	type: 'text'},
            		{label: 'Nom du Compte', 					fieldName: 'nomCompte', type: 'text'},
                    {label: 'Rue', 								fieldName: 'rue', 		type: 'text'},
            		{label: 'CP', 								fieldName: 'cp', 		type: 'text'},
            		{label: 'Ville', 							fieldName: 'ville', 	type: 'text'},
            		{ type: 'action', typeAttributes: { rowActions: actions } }
                ]);
    }


 
var csresults = new Array();
                    
					for (var item of results.companies) {
                        var csresult = new Object();
                        csresult.siret = item.regNo;
                        csresult.nomCompte = item.name;
                        csresult.rue = item.address.street;
                        csresult.cp = item.address.postalCode;
                        csresult.ville = item.address.city;
                        
                        csresults.push(csresult);
                    }
                    
                    
                    component.set('v.csResults', csresults);
                    component.set('v.showCsResults', true);


 
Hello

I am trying to get the record id of the reocrd that was clicked in an aura:iteration.
But instead of getting the value of the id , I get the EL , I don't undrstand why.
 
<aura:iteration items="{!v.doublons}" var="item">
                <lightning:card title="{!item.nomCompteRaisonSociale}" class="slds-m-around_x-small">
                    <aura:set attribute="actions">
                        <ui:button press="{!c.onClickSeeAccount}" aura:id="{!item.recordId}" label="Voir le compte" class="slds-m-around_x-small" />
                    </aura:set>
                    <p class="slds-p-horizontal_small">
                        Siret : {!item.siret} <br/>
                        Rue : {!item.shippingStreet} <br/>
						Code Postal : {!item.codePostal} <br/>
                        Ville : {!item.ville} <br/>
                    </p>
                </lightning:card>
            </aura:iteration>
 
({
	onClickSeeAccount : function(component, event, helper) {
		var searchResults = event.getSource().getLocalId();

	}
})

User-added image
Hello

I want to display different icons in lightning:dataTable based on row condition.
For example
If row1.someField == 'A' then iconName = A
If row2.someField == 'B' then iconName = B

I have looked at documentation but it seems we can specify icons at the colmun level .

This is what I have done so far but it always display the same icon :
 
component.set('v.resultColumns', [
            		{label: 'Provenance', 						fieldName: 'provenance', 				 cellAttributes: { iconName: 'action:call' }}

                ]);

 
Hello
It seems the maxlength attribute is not working on the lightning:input. Ihave put a maxlength of 5 but I can enter more than 5 characters.
<lightning:input aura:id="cpOuDepartement" type="number" label="Code postal ou Département" maxlength="5" name="cpOuDepartement" value="{!v.searchRequest.cpOuDepartement}" />
Am i missing something?
 
I think I am close to passing step 6 but I am getting this error message :
Challenge Not yet complete... here's what's wrong:
We couldn't find the BoatDetails component on the Friends with Boats Lightning page.


I had some layouts in the page so that my components are laid out correctly.
Because of the error message, I thought I am not passing the challenge because my BoatDetails component is surrounded by divs and lightning:layout.
So Iremoved all of them but still, I get the error.

This is what I have left now, please help :
 
<aura:application extends="force:slds" >
	
    <lightning:card title="Find a Boat" class="slds-m-top_xx-large" >
        <c:BoatSearch />
    </lightning:card>

      <c:BoatDetails />

</aura:application>

 
Hello

We want to know in which environment we are when running Apex, more precisely we need to know if we are in Production, or Sandbox A, or Sandbox B, etc..

At the moment, we are looking at Org Id to determine the environment, like this :
 
public static Boolean IsProductionOrg() { // Method to check of environement is Production ORG or not
        return UserInfo.getOrganizationId() == '00ecqzecqc1IkdlUAC' ? true : false; 
    }
    
        /**
     * This method retun whether this org is a production or a sandbox
     * @return true/false
     */
    public static Boolean IsPProdOrg() { // Method to check of environement is PPROD Sandbox or not
       return UserInfo.getOrganizationId() == 'cdscddscdsccsdc'  ? true : false; 
    }

We do not like this method because everytime we refresh the Sandbox, the Org IDs of the Sandboxes change and we have to update the code.

I have found this link :
http://salesforceworld4u.blogspot.com/2015/12/how-to-get-sandbox-name-in-apex.html

It says we can look at the suffix of the logged-in user, then we can find out if it is Sandbox or Production.
For example, if logged-in user is john.smith@mycompany.com.pprod , than means environment is pprod Sandbox.

We also do not like this method because we are afraid users can change their username and remove the suffix, so method will not work anymore.

What is the clean way of doing this?


 
I have a picklist with an onchange event bound to it.
When I select a value in the picklist, I get the following error message :
This page has an error. You might just need to refresh it. Error in $A.getCallback() [b.run is not a function] Failing descriptor: {lightning:select}

Component :
 
<aura:component>
    
    <aura:attribute name="colors" type="String[]"/>
    <aura:attribute name="selectedColor1" type="String"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.loadOptions}" />
    
    <lightning:select aura:id="select1-id" value="{v.selectedColor1}" onchange="{c.onChangeColor}" name="picklist1" label="Select a Color"  >
        <option value="">-- None --</option>
        <aura:iteration items="{!v.colors}" var="color">
            <option value="{!color.value}" text="{!color.label}"></option>
        </aura:iteration>
    </lightning:select>
    
</aura:component>
Controller :
({
    loadOptions: function (component, event, helper) {
        var opts = [
            { value: "R", label: "Red" },
            { value: "G", label: "Green" },
            { value: "B", label: "Blue" }
         ];
         component.set("v.colors", opts);
    },
    onChangeColor: function (component, event, helper) {
        //var myColor = event.getSource().get("v.value");
        //var test;
    }
})


 
We want to use Salesforce DX. For this we need to enable DevHub. We can see the DevHub option in Production, but we cannot see it in our Sandboxes. Please help.
Hello

We want to know in which environment we are when running Apex, more precisely we need to know if we are in Production, or Sandbox A, or Sandbox B, etc..

At the moment, we are looking at Org Id to determine the environment, like this :
 
public static Boolean IsProductionOrg() { // Method to check of environement is Production ORG or not
        return UserInfo.getOrganizationId() == '00ecqzecqc1IkdlUAC' ? true : false; 
    }
    
        /**
     * This method retun whether this org is a production or a sandbox
     * @return true/false
     */
    public static Boolean IsPProdOrg() { // Method to check of environement is PPROD Sandbox or not
       return UserInfo.getOrganizationId() == 'cdscddscdsccsdc'  ? true : false; 
    }

We do not like this method because everytime we refresh the Sandbox, the Org IDs of the Sandboxes change and we have to update the code.

I have found this link :
http://salesforceworld4u.blogspot.com/2015/12/how-to-get-sandbox-name-in-apex.html

It says we can look at the suffix of the logged-in user, then we can find out if it is Sandbox or Production.
For example, if logged-in user is john.smith@mycompany.com.pprod , than means environment is pprod Sandbox.

We also do not like this method because we are afraid users can change their username and remove the suffix, so method will not work anymore.

What is the clean way of doing this?


 
Hi 
Help me with test class


public with sharing class CancelPendingApprovalsOfLostDeals implements Database.Batchable<sObject> {

    public Database.QueryLocator start(Database.BatchableContext context) {
        return Database.getQueryLocator([SELECT Id, StageName FROM Opportunity WHERE StageName='Closed Lost']);
    }

    public void execute(Database.BatchableContext context, List<Opportunity> opportunities) {
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
        for (Opportunity opp: opportunities) {
            oppMap.put(opp.Id, opp);
        }

        OpportunityManagement.CancelApprovalsIfClosed(oppMap);
    }

    public void finish(Database.BatchableContext context){
                
    }
}

Thanks
Hi,
      I have 2 fields in the Event - the first is lookup filed "Status" and the second is date filed "lastAppointmentDate". For tracking purposes. I would like to add the corresponding date to the "lastAppointmentDate field based on when "Status__r.Actual_Status__c"  is updated to "Done".
I'd also like to make the "lastAppointmentDate" field not able to be edited unless you are an admin.
 
Thanks,
Any help would be appreciated.
Hi All,
We want to use the lightning dialer feature on production Org.
We didn't found any document for mobile support of lightning dialer.
Is lightning dialer supported for mobile, polycom phones or cellphones?
 
  • August 23, 2018
  • Like
  • 0
Hi Team,

I am getting salesforce "Apex CPU time limit exceed exception" in the below code. Please help me to optimize the code or how to sort out this issue. Any help would be greatly appriciated. 


public static Map<String, Object> getCFAccountOverdue(Set<String> cfAccountIdSet ) {
    Map<String, Object> cfAccountOverdueMap = new Map<String, Object>();
    Map<String, Decimal> overdueDateRangeMap = new Map<String, Decimal>();
    
    for(Schema.pickListEntry eachVal : CF_Claim__c.Overdue_Date_Ranges__c.getDescribe().getPicklistValues()){
        overdueDateRangeMap.put(eachVal.getValue(), 0);
    }
        for(CF_Claim__c eachClaim : [SELECT CF_Account__c, Overdue_In_Days__c, Amount__c  FROM CF_Claim__c  WHERE CF_Account__c IN:cfAccountIdSet AND Status__c = 'Open' ORDER BY CF_Account__c,Overdue_In_Days__c Nulls last]) {                
            if( !cfAccountOverdueMap.containsKey(eachClaim.CF_Account__c) ) {   
                Map<String, Decimal> dateRangeMap = new Map<String, Decimal>(); 
                dateRangeMap.putAll(overdueDateRangeMap);
                dateRangeMap.put(eachClaim.Overdue_In_Days__c, eachClaim.Amount__c != null ? eachClaim.Amount__c : 0);
                cfAccountOverdueMap.put(eachClaim.CF_Account__c, dateRangeMap);                    
            }else {
                Map<String, Decimal> dateRangeMap = (Map<String, Decimal>)cfAccountOverdueMap.get(eachClaim.CF_Account__c);
                dateRangeMap.put(eachClaim.Overdue_In_Days__c, ((dateRangeMap.get(eachClaim.Overdue_In_Days__c)) + (eachClaim.Amount__c != null ? eachClaim.Amount__c : 0)));
                cfAccountOverdueMap.put(eachClaim.CF_Account__c, dateRangeMap);
            }
        }
    return cfAccountOverdueMap; 
}
  • August 23, 2018
  • Like
  • 0
I have custom object Test__c and it has a time field called Duration__c
Lets Say user enter like 30 minutes in the date field and saved the record, then in the back ground count down timer should start starting from 30 minutes and when it reached 0 then a pop up should show on the service console layout.

If I get any help then it will be really helpful.
Hi, 
I have a requirement where I need to query all the fields of Case object along with all the fields of the Child objects of Case. How do I built a query for the same. Right now I am able to query only the fields of Case object. I am not sure how to design an inner query using dynamic apex.
This is my code snippet
public class TEL_CaseController
{
    public List<Case> caseList{get;set;}
    public List<SObjectType> childList{get;set;}	
    public String query{get;set;}
    public List<String> listFields{get;set;}
    String allFields = '';
    public TEL_CaseController ()
    {
        String SobjectApiName = 'Case';
        
        /*********************************************/
        childList = new List<SObjectType>();
        Schema.SObjectType convertType = Schema.getGlobalDescribe().get(SobjectApiName);
        Schema.DescribeSObjectResult obj = convertType.getDescribe();
        for (Schema.ChildRelationship cr: obj.getChildRelationships()) 
        {
            system.debug('Child Object Name:'+cr.getChildSObject());
            childList.add(cr.getChildSObject());
        }
        
        /*********************************************/
        Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
        Set<string> mapset = fieldMap.keyset();
        caseList = new List<Case>();
        listFields = new List<String>();
        FOR ( String str:mapset )
        {
            
            allFields += str +', '; 
            listFields.add(str);
        }
        allFields = allFields.removeEnd(', ');
        
        query = 'SELECT ' + allFields + ' FROM ' + SobjectApiName + ' where id = \''+apexPages.currentPage().getParameters().get('id')+'\' ';
        caseList = Database.query(query);
    }
}

 
Im maping as map<invoice__c,List<line_item__c>> Now I have to calculate for each invoice sum of quantity(in line item) is greater than 100 ? if its greater then i have to update status in invoice .
Hi All,
      i want to Develop a generic method which can be used in any object’s trigger and it should then start creating History Tracking records.
    how to do it?
Any suggestions?
Hi everyone, I have a situation in which I do a case insert where in this situation the case is account child is only can insert once as I do to insert only once this case because when I execute the method it inserts more at once follow the code
@AURAEnabled
    public static void openNewCasepoliticament(Account contaPessoal){
        try{
            Case caso = new Case();
            //caso.Description = description;
            caso.Origin = 'Plataforma de investimentos';
            caso.Reason  = 'Problema de Cadastro';
            caso.Priority = 'Alta';
            caso.Status = 'Novo';
            caso.Type = 'Problemas de Cadastro';
            caso.SubTipo__c = 'Politicamente Exposto';
            caso.AccountId = contaPessoal.Id;
            insert caso;
            
            
            
        }catch(DMLException dml){
            System.debug('Falha ao inserir caso: ' + dml.getMessage());
            throw new AuraHandledException('Falha ao inserir caso: ' + dml.getMessage());
        }
    }
Hello

We are using STate and Country piclists.
So on Contracts we have a ShippingAddress field that contains a ShippingCountry.

When I visualise a Swiss contract in our Salesforce UI, the ShippingCountry displays as "Suisse" ("Switzerland" in French).
Whiwh is normal because my personal language setting is set to French.

The issue is that when I query this contract with SOQL, the value of ShippingCountry is in English (Switzerland).

How can I get this ShippinCountry value in French when I query with SOQL?

I checked our company-wide settings, default language is also French.

Thanks
 
Contract c = [Select id , shippingcountry from contract where id = '8000Y000000FgEJQA0'];

system.debug('### MAB ' + c.ShippingCountry);

 
Hello

Trying to deploy a validation rukle from one sandbox to another with Workbench.
It is the first time I try, my manager has shown me how to do it the last week, now he is out of the office so I am trying by myself.
I think I am close to the right way but Cannot figure out what is missing.

He showed me that there was two steps : retrieve and deploy.

For the retrieve part I need to provide a package.xml specifying what components I want to retrieve.

So I created the following package.xml file :
 
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
	<types>
		<members>VerifySiret</members>
		<name>ValidationRule</name>
	</types>
	
	<version>43.0</version>
</Package>

But when I go to Migration > Retrieve and provide my file I get this message, validation rule cannot be found :

User-added image

Can someone please explain what I am doing wrong?
I am seeing this error...'Challange Not yet complete...here's what's wrong: The 'Shift Hours' field on the 'Volunteer Shift' record is not working as expected. I'm stuck as to what I am doing wrong. It's probably a simple fix that I'm over looking. Help solving this problem would be greatly appreciated! Thanks!

User-added image
User-added image
User-added image
In my company I was facing a scenario where I had to chain two Apex asynchronous calls:
First I needed to call myApexMethod1 which returns a result myResult
Secondly I needed to call myApexMethod2 but needed to provide myResult as a parameter to the method.


So this is the first version I coded :
 
({
    "myFunction" : function(cmp) {


        var action = cmp.get("c.myApexMethod1");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
               myResult = response.getReturnValue();
            }
        });
        $A.enqueueAction(action);


        var action2 = cmp.get("c.myApexMethod2");
	action2.setParams({ myParam : myResult });
        action2.setCallback(this, function(response) {
            var state2 = response.getState();
            if (state2 === "SUCCESS") {
               //Do something
            }
        });
        $A.enqueueAction(action);


    }
})

This code compiles well but there is a problem:
Since the calls are asynchronous, by the time we reach :
action2.setParams({ myParam : myResult });

it is not guaranteed that myResult is filled, because at that time nothing guarantees that myApexMethod1 has executed since it is asynchronous.

To avoid this behaviour, I decided to nest the second call inside the callback of the first method.
That gives the following code :
 
({
    "myFunction" : function(cmp) {


        var action = cmp.get("c.myApexMethod1");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {

               myResult = response.getReturnValue();

               var action2 = cmp.get("c.myApexMethod2");
	       action2.setParams({ myParam : myResult });
               action2.setCallback(this, function(response) {
                   var state2 = response.getState();
                   if (state2 === "SUCCESS") {
                        //Do something
                   }
               });
               $A.enqueueAction(action);

            }
        });
        $A.enqueueAction(action);

    }
})

I have tested it and it works.

But my question is:
Is it the proper way to chain these asynchronous calls?
Next time maybe I will have to chain a lot of asynchronous calls and this pattern does not look very clean?
Is there a better practice to chain these asynchronous calls?