• Maharajan C
  • ALL STAR
  • 9254 Points
  • Member since 2015
  • Sr.Associate Consultant
  • Infosys


  • Chatter
    Feed
  • 308
    Best Answers
  • 2
    Likes Received
  • 4
    Likes Given
  • 14
    Questions
  • 1088
    Replies
I need help writing a test class for my apex code. I really don't know much about apex. But I was able to create a visualforce page and an apex class that extends the standard controller. Everything works perfectly in my sandbox. But I have no idea how to write the test class so that I can push my code into production.

Here is my code for the visualforce page:

<apex:page standardController="WorkOrder" extensions="WorkOrderLineItemsOnWorkOrderClass">     

    <apex:sectionHeader title="Equipment on quote number {! WorkOrder.Workorder_Name__c } for {! WorkOrder.Account.Name }"/>
  
    <p></p>
    
    <apex:pageblock id="WorkOrderLineItemList"> 

         <br/> 

            <apex:pageBlockTable value="{!WorkOrderLineItems}" var="item">                          

                <apex:column value="{!item.Product_Code_Display__c}"/>
                
                <apex:column value="{!item.Description}"/> 
                
                <apex:column value="{!item.Quote_Line_Quantity_Display__c}"/>
                
                <apex:column value="{!item.Quote_Line_Net_Total_Display__c}"/> 
                
                <apex:column value="{!item.Group_Name__c}"/>
               
            </apex:pageBlockTable>     
            
     </apex:pageblock> 

</apex:page>

And here my code for my apex class that extends the standard controller:

public class WorkOrderLineItemsOnWorkOrderClass {

    public List<WorkOrderLineItem> WorkOrderLineItems{get;set;}

    public WorkOrder WorkOrders {get;set;} 

    public WorkOrder wo {get;set;} 

     //Constructor 

    public WorkOrderLineItemsOnWorkOrderClass(ApexPages.StandardController controller) { 

        wo = (WorkOrder)controller.getRecord();      

        WorkOrders = [SELECT id FROM WorkOrder WHERE id=: wo.id LIMIT 1]; 

        WorkOrderLineItems = [SELECT id,Group_Name__c,Product_Code_Display__c,Quote_Line_Quantity_Display__c, Description, Quote_Line_Net_Total_Display__c FROM WorkOrderLineItem WHERE WorkOrderid = :WorkOrders.id ORDER BY Quote_Line__c];     


   
}
 
trigger contactTrigger on Contact (after insert,after update) {
List<Id> ids = new List<Id>();
    for(Contact con: trigger.new){
        ids.add(con.AccountId);
    }
    List<Account> aList= [select id,name, Task__c, (select id,Task__c from contacts) from account where id IN: ids];
        
    
    for(Account acc: aList){
        for(Contact con: acc.contacts){
            system.debug('task'+con.Task__C+acc.Task__C);
        if(con.Task__C=='Submitted'){
            acc.Task__C='Achieved';
            } system.debug('task'+con.Task__C+acc.Task__C+acc.Name);
        }
    }
}
    
    
    
    
    
    
    
    
 
I found this How To Show HTML Email Right On Your Case Page (http://success.salesforce.com/ideaView?id=087300000007TOe) that really works great for what we want but cannot understand how to test it.
 
public with sharing class CaseHTMLEmailController {
    private final Case caseObj;

    public String firstHTMLEmail { get
        {return getFirstHTMLEmail(); }
    }
    
    public CaseHTMLEmailController(ApexPages.StandardController stdController) {
        this.caseObj = (Case)stdController.getRecord();
    }

    public String getFirstHTMLEmail() {
        EmailMessage firstEmail = [Select HtmlBody From EmailMessage where ParentId=:caseObj.Id order by LastModifiedDate asc limit 1];
        if (firstEmail!=null) {
            return firstEmail.HtmlBody;
        }
        
        return '';
    }
}

I need the email-to-case context where the case was generated by an email and test  it pulling the data from emailMessage for this visualforce page.
Hello,

I have a map with Name(String) and Ranks(Integer),
Name is the Pricebook name and Rank is Order by.
map<String,Integer> mapOfNameAndRank = new map<String,Integer>();

Name1, 1
Name2, 2
Name3, 3
I am populating SelectOption in below manner: 
public list<SelectOption> listOfOpt {get;set;}
for(priceBook2 prc : [select id,Name from priceBook2 ){
            listOfOpt.add(new SelectOption(prc.Id,prc.Name));
        }

My usecase is that, the SelectOption should display the Name is the order defined in map.

How can i reiterate the SelectOption inorder to order it.

thank you for suggestion
Params1:
public class params1 {
    @AuraEnabled
    public static List<Account> accountthod(){
        List<Account> accounts=[select id,name,industry,rating,phone from Account limit 4];
        return accounts;
    }
}

pasasm.cmp
<aura:component controller="params1">
    <aura:attribute name="acclist" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.invoke}"/>
    <aura:iteration items="{!v.acclist}" var="a">
        <p>{!a.name} &nbsp;&nbsp;&nbsp;{!a.industry} &nbsp;&nbsp;&nbsp;{!a.rating} &nbsp;&nbsp;&nbsp;{!a.phone}</p>
    </aura:iteration>
</aura:component>

parasmController.js
({
    invoke : function(component, event, helper) {
        var action=component.get("v.accountthod");
        action.setCallback(this,function(response){
            console.log("invoked");
            var state=response.getState();
            if(state==='SUCCESS'){
                console.log('Operation successfull');
                component.set("v.acclist",response.getReturnValue());
            }else{
                console.log('Operation failed');
            }            
        });
        $A.enqueueAction(action);
    }
})

parasmap.app
<aura:application extends="force:slds">
    <c:parasm />
</aura:application>
I am trying to get the Contact Name and Email of the Primary Opportunity Contact. I am having difficulty as what is being returned is the Id of the contact and no email. 

Could someone let me know what key piece I'm missing here? 
 
List<OpportunityContactRole> primaryContactInfo = [SELECT OpportunityId, Contact.Name, Contact.Email
                    FROM OpportunityContactRole
                    WHERE OpportunityId ='0063h00000551YKAAY' AND isPrimary = TRUE];

System.debug(primaryContactInfo[0].get((string)'OpportunityId'));
System.debug(primaryContactInfo[0].get((String)'ContactId'));

How would I expose Contact.Name and Contact.Email? 
Can't do with Workflow or Process Builder...can I do this with a Trigger? New to Triggers

Trying to update a custom field (Call_Copy_Last_Reported_Date__c) on User object with a date (Week_Ending__c) from custom object (Call_Copy_Reporting__c) when a new Call Copy Report is created. 

Custom Object - Call Copy Reporting
Owner (Lookup)
Week_Ending__c (Date)

User Object
Call_Copy_Last_Reported_Date__c (Date)

Any help would be appreciated!
Hi, i write a code about datatable and apex, but  the result is null.
I have a custome object called Warehouse.It have a relationship field, related to Product object. And a number filed called Amount.
 want to show they in datatable. Now page show null but amount of records is right. And i try to show Name,Type__c , they will show. Just Product__r.Name and Amount__c is null.
Im sure that my SOQL is right.because i run it in develope consle query editor.

This is my code.
cmp:
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
	<aura:attribute name="columns" type="List"/>
	<aura:attribute name="data" type="Object"/>
	<aura:attribute name="errors" type="Object" default="[]"/>

	<lightning:card title="Pending QA">
		<lightning:datatable
			columns="{! v.columns }"
			data="{! v.data }"
			keyField="Id"
			errors="{! v.errors}"
			hideCheckboxColumn="true"/>
	</lightning:card>
controller:
doInit : function(component, event, helper) {
    	component.set('v.columns', [
            { label: 'Product', fieldName: 'Product__r.Name', type: 'text',editable:false},
            { label: 'Amount', fieldName: 'Amount__c', type: 'text',editable:false}]);
    	helper.getPendingRecord(component,event,helper);
    }
Helper:
getPendingRecord : function(component, event, helper) {
		var action = component.get("c.query");
        // call back
        action.setCallback(this, function(response){
            var state = response.getState();
            // call back success
            if (state == "SUCCESS"){
                var result = response.getReturnValue();
                component.set('v.data', result);
            }
            // call back failed
            else {
                var toastEvent=$A.get("e.force:showToast");
                toastEvent.setParams({
                    "title":'Error!',
                    "message":'Get Record Failed!',
                    "duration":5000,
                    "type":ERROR
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);
	}
class:
public static List<Warehouse__c> query() {
    	List<Warehouse__c> pending = new List<Warehouse__c>();
        pending = [SELECT Product__r.Name,Amount__c FROM Warehouse__c WHERE Type__c = 'pendingArea'];
        return pending;
    }
Pls help me. Thanks!


 
CMPT:
<aura:component controller="DTController">
    <aura:attribute name="parentId" type="Id"/>
    <aura:attribute name="nameFilter" type="string"/>
    <aura:attribute type="FIN_RCSAQ__c[]" name="acctList"/>
    <aura:attribute name="showSaveCancelBtn" type="boolean" default="false" />
    <aura:attribute name="isAsc" type="boolean" default="true" description="boolean flag for pass sorting condition to apex class"/> 
    <aura:attribute name="arrowDirection" type="string" default="arrowup" description="Use for change arrow sign direction on header based on click"/>
    <aura:attribute name="selectedTabsoft" type="string" default="firstName" description="Use for show/hide arraow sign on header based on conditions"/>
     
    <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/>
    
    <table class="slds-table slds-table_bordered slds-table_col-bordered slds-table_cell-buffer slds-table_edit slds-table_resizable-cols" style="table-layout: fixed; width: 100% !important;">
        <thead>
            <tr class="slds-line-height_reset">
                <th class="slds-is-sortable" scope="col" onclick="{!c.sortName}">
                    <a href="javascript:void(0);" class="slds-th__action slds-text-link--reset">
                        <span class="slds-assistive-text">Sort</span>
                        <span class="slds-truncate" title="Name">Fin-RSCAQ</span>  
                        <aura:if isTrue="{! and(v.arrowDirection == 'arrowdown', v.selectedTabsoft == 'Name') }">
                            <lightning:icon iconName="utility:arrowdown" alternativeText="Descending" size="xx-small" />
                        </aura:if>  
                        <aura:if isTrue="{! and(v.arrowDirection != 'arrowdown', v.selectedTabsoft == 'Name') }">
                            <lightning:icon iconName="utility:arrowup" alternativeText="Descending" size="xx-small" /> 
                        </aura:if>                        
                    </a>
                </th>
                <th class="slds-is-sortable" scope="col" onclick="{!c.sortControlNumber}">
                    <a href="javascript:void(0);" class="slds-th__action slds-text-link--reset">
                        <span class="slds-assistive-text">Sort</span>
                        <span class="slds-truncate" title="ControlNumber">Control Number</span>  
                        <aura:if isTrue="{! and(v.arrowDirection == 'arrowdown', v.selectedTabsoft == 'ControlNumber') }">
                            <lightning:icon iconName="utility:arrowdown" alternativeText="Ascending" size="xx-small" />
                        </aura:if>  
                        <aura:if isTrue="{! and(v.arrowDirection != 'arrowdown', v.selectedTabsoft == 'ControlNumber') }"> 
                            <lightning:icon iconName="utility:arrowup" alternativeText="Descending" size="xx-small" />
                        </aura:if>                        
                    </a>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="ControlObjective">Control Objective</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="ControlledElsewhere">Controlled Elsewhere</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="ControlledElsewhereHFMCode">Controlled Elsewhere HFM Code</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="Frequency">Frequency</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="FrequencySelection">Frequency Selection</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="Preparer">Preparer</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="CreatedBy">Created By</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="FirstApprover">First Approver</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate slds-text-align_center" title="SecondApprover">Second Approver</div>
                </th>
            </tr>
        </thead>
        <!--table body start, Iterate contact list as a <tr> -->
        <tbody>
            <aura:iteration items="{!v.acctList}" var="acc">  
                <c:InlineEditRow singleRec="{!acc}" 
                                 rcsaqFrequencyVal="{!acc.RCSAQ_Frequency__c}" 
                                 frequencySelectionVal = "{!acc.Frequency_Selection__c}"
                                 firstOwnerNameVal="{!acc.First_Approver__r.Name}" 
                                 secondOwnerNameVal="{!acc.Second_Approver__r.Name}" 
                                 prepareNameVal="{!acc.Preparer__r.Name}" 
                                 showSaveCancelBtn="{!v.showSaveCancelBtn}"/>
            </aura:iteration>
        </tbody>
    </table> 
    
    <aura:if isTrue="{!v.showSaveCancelBtn}">
        <lightning:buttonGroup class="slds-m-around_medium">
            <lightning:button label="Cancel" />
            <lightning:button label="Save" onclick="{!c.handleSaveEdition}" variant="success"/>
        </lightning:buttonGroup>
    </aura:if> 
</aura:component>

Controller:
({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, "Name");
    },
    sortName : function(component, event, helper) {
        component.set("v.selectedTabsoft", "Name"); 
        helper.sortHelper(component, event, "Name");
    },
    sortControlNumber : function(component, event, helper) {
        component.set("v.selectedTabsoft", "ControlNumber"); 
        helper.sortHelper(component, event, "Control_Number__c");
    },
    handleSaveEdition: function (cmp, event, helper) {
        var draftValues = cmp.get("v.acctList");
        console.log(draftValues);
        var action = cmp.get("c.updateAccount");
        action.setParams({"acc" : draftValues});
        action.setCallback(this, function(response) {
            console.log(response);
            helper.fetchAccHelper(cmp, event, "Name");
            cmp.set("v.showSaveCancelBtn", false); 
        });
        $A.enqueueAction(action);
    },
})

Helper:
({
    fetchAccHelper : function(component, event, sortFieldName) {
        var action = component.get("c.fetchAccount");
        action.setParams({
            "parentId" : component.get("v.parentId"),
            "sortField": sortFieldName,
            "isAsc": component.get("v.isAsc"),
            "nameLike":component.get("v.nameFilter")
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var records =response.getReturnValue();
                console.log(records);
                records.forEach(function(record){
                    record.linkName = '/'+record.Id;
                });
                component.set("v.acctList", records);
            }
        });
        $A.enqueueAction(action);
    },
    sortHelper: function (component, event, sortFieldName) {
        var currentDir = component.get("v.arrowDirection");
        if (currentDir == 'arrowdown') {
            component.set("v.arrowDirection", 'arrowup'); 
            component.set("v.isAsc", true);
        } else {
            component.set("v.arrowDirection", 'arrowdown');
            component.set("v.isAsc", false);
        }
        this.fetchAccHelper(component, event, sortFieldName);
    }
})
Style:
.THIS .slds-table td th {
    white-space:normal; /* wraps larger stuff like textarea and long text*/
}
.THIS .widthVal {
    max-width:100% !important;
}

Apex Class:
public class DTController{
    @AuraEnabled
    public static List<FIN_RCSAQ__c> fetchAccounts(String parentId) {
        String query = 'SELECT Id, Name, Control_Number__c, Question_Number__c, Risk_Reference__c, Control_Objective__c,';
        query += 'Group_Control_Description__c,Assertions__c,Controlled_Elsewhere__c,Controlled_Elsewhere_HFM_Code__c,';
        query += 'First_Approver__c,First_Approver__r.Name,Second_Approver__c,Second_Approver__r.Name,';
        query += 'Frequency_Selection__c,RCSAQ_Frequency__c,Preparer__r.Name,';
        query += 'Control_Clarification__c,Frequency__c,Control_Type__c,System_Report_SAP__c,System_Report_OTC__c,System_Name__c,';
        query += 'Excel_File_Name__c,Evidence_of_the_Control__c,Notes_Guidance__c,Preparer__c,Supported_By__c FROM ';
        query += 'FIN_RCSAQ__c WHERE Control_Number__c LIKE \'RR%\'';
        if(String.isNotBlank(parentId)) query += ' AND FIN_RCSA__c = \'' + parentId + '\'';
        List<FIN_RCSAQ__c> accList = Database.query(query);
        System.debug(accList);
        return accList;
    }
    
    @AuraEnabled
    public static List<FIN_RCSAQ__c> fetchAccount(String parentId, String sortField, boolean isAsc, String nameLike) {
        String query = 'SELECT Id, Name, Control_Number__c, Question_Number__c, Risk_Reference__c, Control_Objective__c,';
        query += 'Group_Control_Description__c,Assertions__c,Controlled_Elsewhere__c,Controlled_Elsewhere_HFM_Code__c,';
        query += 'Control_Clarification__c,Frequency__c,Control_Type__c,System_Report_SAP__c,System_Report_OTC__c,System_Name__c,';
        query += 'Preparer__r.Name,First_Approver__c,First_Approver__r.Name,Second_Approver__c,Second_Approver__r.Name,';
        query += 'Frequency_Selection__c,RCSAQ_Frequency__c,';
        query += 'Excel_File_Name__c,Evidence_of_the_Control__c,Notes_Guidance__c,Preparer__c,Supported_By__c FROM ';
        query += 'FIN_RCSAQ__c WHERE Control_Number__c LIKE \'' + nameLike + '%\'';
        if(String.isNotBlank(parentId)) query += ' AND FIN_RCSA__c = \'' + parentId + '\'';
        if (sortField != '') {
            query += ' order by ' + sortField;
            query += isAsc ? ' asc' : ' desc';
        }
        
        system.debug('The query is ' + query);
        return Database.query(query);
    }
    
    @AuraEnabled
    public static String getContactName(String conId) {
        String conName;
        List<Contact> conList = [Select Id,FirstName,LastName from Contact Where Id =: conId];
        if(conList.size() > 0)
            conName = String.isNotBlank(conList[0].FirstName) ? conList[0].FirstName + ' ' + conList[0].LastName : conList[0].LastName;
        System.debug(conName);
        return conName;
    }
    
    @AuraEnabled
    public static String getUserName(String conId) {
        String conName;
        List<User> conList = [Select Id,FirstName,LastName from User Where Id =: conId];
        if(conList.size() > 0)
            conName = String.isNotBlank(conList[0].FirstName) ? conList[0].FirstName + ' ' + conList[0].LastName : conList[0].LastName;
        System.debug(conName);
        return conName;
    }
    
    @AuraEnabled
    public static void updateAccount(List<FIN_RCSAQ__c> acc ){
        update acc;
    }
}

 
For some reason, my Contact object still shows existing contacts inside my unit tests even though I am not using seeAllData=true...
 
@isTest
public class TravelDetailGateway_Tests {
    @isTest
    public static void loadData_Tests() {
        Test.loadData(Account.sobjectType, 'test_data_accounts'); //file contains 10 rows.
        //contact in file is associated to account 9 in the file above.
        Test.loadData(Contact.sobjectType, 'test_data_contacts'); //file coontains 1 row.
        
        integer acctCount = [SELECT count() FROM Account];
        integer ctcCount = [SELECT count() FROM Contact];
        
        system.assertEquals(10, acctCount);
        system.assertEquals(1, ctcCount); //assertion fails and returns 11 records.
    }
}

 
Importing from this CSV file:
"OWNERID","STATUS","ORIGIN","SUBJECT","PRIORITY","DESCRIPTION"
"3D00G1U000002xbcg","New","EMAIL","New order.","HIGH","Seven TwentyOne Main"

Gives me this success message showing new ID :
"ID","OWNERID","STATUS","ORIGIN","SUBJECT","PRIORITY","DESCRIPTION","STATUS"
"5002900000BrQN4AAN","3D00G1U000002xbcg","Item Created","EMAIL","New subscription renewal order.","HIGH","Seven TwentyOne Main","Item Created"
A Case is created but the detail is missing, Origin is blank, owner is me, not the OwnerId, subject blank, descriptrion blank, Just ... Nothing but the defaults for Status and Priority

I disabled the trigger.
Hi I am somewhat of a novice when it comes to apex and can't seem to work out what the problem is with line 7 of my code. I am building a practice trigger that creates 10 identical opportunities whenever an account has more than 99 employees.

I think I have set up the for loop correctly but in the developer console 'Problem' there are a number of messages on line 7
- Expecting ';' but was a '<'
- Expecting ';' but was a ','
- Expecting ';' but was a ')'

Any suggestions?
trigger CreateTenOpps on Account (before insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 100) {
            for (Integer i = 0, i < 10, i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', Name = 'Trigger Opp');
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 

Hello, I wrote a trigger to check if the url = 'https://sig-cb--Full.cs88.my.salesforce.com' and the profile of the current user is a specific profile (SIG-FSM-Super User) and if so the trigger shows an error message and also an image which I included in the addError function, it looks like this:

trigger ContactCreationForServiceMaxUsers on Contact (Before insert) {
   
       String baseURL = String.valueof(URL.getSalesforceBaseUrl());
      
       system.debug('<<baseURL>>' + baseURL);
       Boolean isBaseURL = baseURL.contains('https://sig-cb--Full.cs88.my.salesforce.com');
       System.debug(' >> String.valueof(URL.getSalesforceBaseUrl()) >>'+baseURL ); 
       User currentUser = [SELECT Id, Profile.Name FROM USER WHERE Id =:UserInfo.getUserId()]; 
      
       Contact c = new Contact(); 
      
       System.debug(' >> isBaseURL >>'+isBaseURL ); 
       System.debug(' >> currentUser.Profile.Name>>'+currentUser.Profile.Name ); 
   
     for(Contact c : Trigger.New){ 
          if(isBaseURL == TRUE  && currentUser.Profile.Name == 'SIG-FSM-Super User'){
           c.addError(' <p style="color:red; font-size: 20px;">Service contact creation is only allowed from “Account” tab using the blue button “Create Contact” after selecting a account”</p><img id="theImage" src="https://sig-cb--full--c.cs88.content.force.com/servlet/servlet.FileDownload?file=0159E0000002tNp" width="850px" height="100px" alt="Description of image here"/> ', false); 
          } 
     } 
}


Can anyone help me with how to build the test class for the trigger? At least theoretical.

1. First I need to create a contact
2. I need to create a user with a profile = 'super-user'
3. somehow i need to check the addError function..

Something like this...

Hi All,

I was given this sample JSON by our partner and I am trying to write a REST Web service to ingest it but I can't seem to get it to work. I am testing it in Workbench and am getting this error:

Unexpected parameter encountered during deserialization: orderNumber at [line:2, column:17

Here is the Apex Class:
 
@RestResource(urlMapping='/DPS_Response/')
global with sharing class DPSResposnse
{
    global class AllParties
    {
        global String partyId;
        global String decision;
    }    
    
    @HttpPost
    global static String updateDPSData    (String orderNumber, AllParties[] parties)
    {
       return 'test';
    }
}

And here is the sample JSON:
{
    "orderNumber":"000042289",
    "parties":
       [
      {
        "partyId": "12345",
        "decision":    "D"    
      },
      {
        "partyId": "09876",
        "decision":    "P"        
      }

       ]
}

 
I had built a trigger in Sandbox, which finds duplicates (with the same external id) and it creates a hyperlink (in the form of a date) on the new record, to be able to link to the old record. I will show you the piece of the code that does that below. However, I accidentally forgot to change the hyperlink from the sandbox link to the production link. I now need to change all the vlaues of those hyperlinks in production. I tried something in the execute anonymous window as a test, but it didn't seem to work. I'll show you both the piece of the Handler and the attempt that I made in the execute window. 

HANDLER:
                string pdi = discharge.Previous_instances__c;
                string disId = discharge.id;
                date disDate = discharge.Discharge_Date__c;
                integer day = oldDischargeMap.get(discharge.Id).Discharge_Date__c.day();
                integer month = oldDischargeMap.get(discharge.Id).Discharge_Date__c.month();
                integer year = oldDischargeMap.get(discharge.Id).Discharge_Date__c.year();
                string dateDisplay = month + '/' + day + '/' + year;
                if(pdi == null){
                    pdi = '';}
                else{
                    pdi = pdi;}
                
                newDischarge.previous_instances__c = pdi+' '+ '<a href=https://centers--partial.lightning.force.com/'+disId+'>'+dateDisplay+ '</a>' + ' ; ' ;

EXECUTE TRIAL
list<discharge__c> disch = [select previous_instances__c from discharge__c ];
for (discharge__c dis: disch){
    if (dis.previous_instances__c != null){
    string link = dis.previous_instances__c;
    link = link.replace('<a href=https://centers--partial.lightning.force.com/', '<a href=https://centers.lightning.force.com/');
    dis.previous_instances__c = link;
        update dis;
    }}
 
Hello,

I have below config:
Account
   Oppourtunty
     Quote
       field (LookUptoAccount__c)
I have below usecase,
When an account is updated on Opportunity, i want that all the quotes should update LookUptoAccount__c with the name of account, 

how can i do it ? workfow or rocessbuilder, thank you in advance
Do anyone have idea to pass the Selectlist value to the Javascript in Salesforce using Document.Element.id .

i need to get the selected value as an alert ;;
 Please let me know how can i get the values , using the javascript Element.id Only

Or provide useful links will go through it .. 
<apex:page id="pg" >
  
 <apex:form id="frm">
 
 <script>
      
      function  getvalue(){
        alert("hi");
       var selectedvalue =document.getElementById("pg:frm:otptpanel:selectlist").value; 
       alert(selectedvalue);
      }
     
      </script>
  <apex:outputPanel id="otptpanel" >
   
    <apex:selectList id="selectedval" size="1" onchange="getvalue()"> 
   <apex:selectOption itemLabel="Hyderbad" itemValue="Hyd"/>
     <apex:selectOption itemLabel="Banglore" itemValue="Ban"/> 
      <apex:selectOption itemLabel="Chennai" itemValue="Che"/>  
    
   </apex:selectList>
  
      </apex:outputPanel>
  
   
 
 
 </apex:form>
 
</apex:page>

using the Javascript Element only .. 
Thanks
Deepika
 
I’m working on my first Visualforce page and controller. Thanks to others on the community, I’ve gotten everything to work and now I need to write the test class to move it to production. I’ve never done this before. I’ve completed the Apex Testing module in Trailhead, but I’m still lost on how to create the test for my project. This just is not clicking for me. Below is my code for the Visualforce page and for the controller. Help is greatly appreciated.

<apex:page StandardController="Contract" extensions="ContractProductsController">
  <apex:form >
        <apex:pageBlock >
                       <apex:pageBlockTable value="{!lineItems}" var="oli">
                 <apex:column >
                  <apex:facet name="header">Product Code</apex:facet>
                       {!oli.PricebookEntry.Product2.ProductCode}
                </apex:column>
                <apex:column >
                    <apex:facet name="header">Product</apex:facet>
                       {!oli.PricebookEntry.Name}
                </apex:column>
              </apex:pageBlockTable>  
          
          </apex:pageBlock>
    </apex:form>
</apex:page>


Controller:

public class ContractProductsController {
 public List<OpportunityLineItem> lineItems { get; set; }
   
    Public ContractProductsController( ApexPages.StandardController std )
                {
                                if( std.getRecord().Id != null )
                                {
                                                Contract con = [ Select Id, Opportunity__c from Contract where Id =: std.getRecord().Id ];
                                               
                                                lineItems = [ Select Id, OpportunityID, PricebookEntry.Name, PricebookEntry.Product2.ProductCode,Product2ID,PricebookEntryID
            from OpportunityLineItem where OpportunityID =: con.Opportunity__c ];
                                }
                                else
                                {
                                                lineItems = new List<OpportunityLineItem>();
                                }
    }        
}
I am trying to display the value of a related custom object field along with the parent fields on my component html.
Here is the SOQL - The below works, I get the data of the child object with the values from the object
SELECT Name,sumchans__Province_Code__c,
    (select sumchans__Penetration__c, sumchans__Total_Units__c,sumchans__On_Billings__c, sumchans__Date_Of_Calculation__c 
    from sumchans__City_Stats__r) FROM sumchans__CITY_MASTER__c
Here is the wire service code:
import { LightningElement, wire } from 'lwc';
import getCityStats from '@salesforce/apex/mduMarketAnalysisController.getCityStats';  
export default class MduPenetration extends LightningElement {
    @wire(getCityStats)cityMaster;        
}

And here is the Component HTML. This just shows the parent fields values not anything from the child, but I don't get any errors.
 
<template if:true={cityMaster.data}>
            <template for:each={cityMaster.data} for:item="city">
                <lightning-layout horizontal-align="center" key={city.Id}>
                    <lightning-layout-Item>
                        {city.Name}
                    </lightning-layout-Item>
                    <lightning-layout-Item>
                        {city.sumchans__City_Stats__r.sumchans__Total_Units__c}
                    </lightning-layout-Item>
                </lightning-layout>                  
            </template>


 
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
We have the managed package which is created by us so we are try to install this package  some other org.

It works fine in all orgs but in one org we have the error message like below:

 (UpdateAcc-2) myrule_1_A1(Action Call) – We can’t find an action with the name and action type that you specified

The UpdateAcc is the Process builder which call the Apex Class.

In the package also we have these components but we got the Error!!!

Any one please help on this!!!

Thanks,
Raj
Hi Experts,

Hope some one wil help me:

Salesforce going to update the certificates. Please refer the below Link.

https://help.salesforce.com/articleView?id=000269027&language=en_US&type=1

So Here i have to do the test compatibility  in my environment for MiddleWare and Integration:

Can any one please let me know how to perform the below steps: 

For Middleware/Integrations
To test the compatibility of an API client that uses SOAP to communicate with Salesforce:
  • Set up an API client in a test environment.
  • In that test environment, change the API client's login endpoint hostname fromlogin.salesforce.com or [MyDomain].my.salesforce.com tohttps://certtest.force.com.
  • As an example, changehttps://login.salesforce.com/services/Soap/u/32.0 to https://certtest.force.com/services/Soap/u/32.0 while leaving the path as-is.
  • Log in with that API client.
  • If you see an error message that resembles the following: "INVALID_LOGIN: Invalid username, password, security token; or user locked out." or “Content is not allowed in prolog.”, then this test passed and your integration trusts DigiCert-signed certificates.
    • The presence of this response means that the underlying TLS connection was successful, despite the higher-level error. The TLS connection is the focus of this test.
  • If you instead see an error message that involves TLS or HTTPS, then the test has failed. Your API client will require adjustments to its list of trusted certificate authority certificates to trust DigiCert-signed certificates.
 
To test the compatibility of an API client that uses REST to communicate with Salesforce: Thanks,
Raj

 
We are using the chatter answers in community which is going to retire after Winter 18 release. Wanted some suggestions to perform the migration...below are the research...
Investigated on Q&A Migration App but wanted to know if someone has used this and its outcome. Was there any data impact? If yes, then how can we overcome that?.
What is the alternative? Is data loader an option?
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(Job Location : Any where).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
Hi All,

Please help me to get a job. Currently am working as Salesforce Developer with 2.7 years of experience.

Am ready to join immedialy to any where(India or Any Country).

Please some one can help me!!!

i got 50+ best answers in this forum and member from 2015.

Thanks,
Maharajan.C
+91-9042584107
maharaja0393@gmail.com
 
Hi All,

Can you please help me to find unused apps in my salesforce instance to Metadata Cleanup

Thanks,
Raj
Hi All,

Can anyone please give a example third party app name to calculate the Opportunity Stage Duration (inbetween stages also).
Example : Proposal,Qualified,Ready Invoice,Negoatiation,Closed won.
In there i want to calculate the stage duration from Qualified to Closed won.Starting stage must be Qualified End stage Closed won
Qualified to Ready Invoice =?
Ready Invoice to Negoatiation =?
Negoatiation to Closed won =?

And also for Sales vs Quota report third party App.

Thanks,
Raj
Hi All,

Can you please anyone give a test class for me to the below Apex Class.

Public class AccountDisplatRecClsExtn{
Public id Current_Acc_Id;
    public AccountDisplatRecClsExtn(ApexPages.StandardController controller) {
Current_Acc_Id = controller.getRecord().id;
    }
     

  public List<Question__c> getcontList(){
   List<Question__c> accList = [select id,Name,AssessmentId__c,AssessmentId__r.Name,External_ID__c,Friendly_Name__c,Question_Plain__c,Question_Style__c,Sort_Order__c,(Select Id,Name,Red_Flag__c,Scoring__c from answers__r) from Question__c where AssessmentId__c=:Current_Acc_Id ORDER by Sort_Order__c ASC];
   return accList;
  
  }
    }

Thanks,
Raj
 
Hi,

In my salesforce org when i convert a lead it creates multiple account,contacts and opportunities at the same time and when i see the created by timings and created by user both are same.

http://docs.releasenotes.salesforce.com/en-us/spring16/release-notes/rn_sales_leads_edit_converted_leads.htm

In above link there is an article i studied about permission set which will enalble us to create multiple account,contacts and opportunities and we can able to view lead again in salesforce detail page but i disabled this options.

Even though i disabled this option i have duplicates created in my salesforce org and i have lead which i can edit on detail page after it converted...I didn't have any trigger.

Please help !!!!!!!!

Thanks,
Raj
Hi Friends,

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
Hi All,

Please Help!!!
Evaluation Criteria : Evaluate the rule when a record is created, and any time it's edited to subsequently meet criteria
Rule Criteria Opportunity :  StageEQUALSClosed Won
Workflow Action : Email Alert

>Here First my record meet the above rule criteria based on the evaluation criteria it sends an an Email i.e Opportunity stage equals Closed   Won
>After that in that same record i change the Opportunity stage to Need Analysis so now the record dont met the criteria so there is a no        Email
>Then i changed that Opportunity record stage to Closed Won now the record meet the criteria so its send an email again but i want to stop    the Sending an Email Now.


Thanks in Advance!!!
Raj.
Hi All,

Any One  please help me to code coverge because i got only 43% coverage

ApexTrigger :-
trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Lead_Campaign__c tm;//Assinging Custom setting To the variable tm
    tm=Lead_Campaign__c.getorgdefaults();
    String Template=tm.Email_Template_ID__c;
    Decimal Days=tm.Threshold_Days__c;
     
    list <CampaignMember> theCampaignMembers = new list<CampaignMember>();
    for(CampaignMember campMem : Trigger.new){//
    if(test.isRunningTest()){
        
        Days = 0;
    }
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
            theCampaignMembers.add(campMem);
         
            }
    // List containing Campaign Member records to be inserted  
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Status,Lead_age__c, owner.email from Lead where id IN : LeadIds])
    try
    {

    if(ld.Status!='Qualified'&&ld.Lead_age__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
 
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
      mail.setTargetObjectId(ld.OwnerId);    
      mail.setWhatId(ld.id);
      mails.add(mail);
      Messaging.sendEmail(mails);
  
}
}
 catch (Exception e)
{

  ApexPages.addMessages(e);
  Profile adminProfile = [Select id From Profile Where Name='System Administrator' Limit 1];

     Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
     List<String> toAddresses = new List<String>();
     toAddresses.add(adminProfile.id);
     mail.setToAddresses(toAddresses);
     mail.setSenderDisplayName('Apex error message');
     mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
     mail.setPlainTextBody(e.getMessage());
     Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
  
}
}


Test Class -:

@isTest(SeeAllData = true)
public class sendNotificationTrigger
{
static testMethod void sendNotificationTrigger ()
{
     Test.startTest();      //Creates Contact to be linked to Campaign Member
Campaign cp =  [SELECT Id FROM Campaign LIMIT 1];
       //Creates a new campaign memeber, associaites it with 1 campaign
 Lead t1 = new Lead(Company= 'TestLead', LastName= 'TestL', Email = 'none@test.com',Status = 'Open' );
 insert t1;
 CampaignMember newMember = new CampaignMember (LeadId = t1.id, status='Sent', campaignid = cp.id);
 insert newMember;
 system.assertequals(t1.status,'Open')  ;

  
 
   
 Test.stopTest();
 }


Thanks,
Raj.
Hi All,

Can any one Please help to write a test class to my Trigger


trigger sendNotificationTrigger on CampaignMember (after insert) {
    Set<Id> LeadIds = new Set<ID>();
    Test_Setting__c tm;//Assinging Custom setting To the variable tm
    tm=Test_Setting__c.getorgdefaults();
    String Template=tm.Template__c;
    Decimal Days=tm.Threshold_Days__c;
     
    
    for(CampaignMember campMem : Trigger.new){//
        if(campMem.leadid != null){
            LeadIds.add(campMem.leadid);
         
            }
            
    List<Messaging.SingleEmailMessage> mails =new List<Messaging.SingleEmailMessage>();   
    for(Lead ld : [select id, Lead_age__c, Status, owner.email from Lead where id IN : LeadIds])
    if(ld.Status!='Qualified'&&ld.Lead_Age_In_days__c>=Days)
    //Checking Condition Status not equal to Qualified and Lead_Age_In_days__c greater than equal to 30
    {
     Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();// For Email
                             
      List<String> sendTo = new List<String>();
      sendTo.add(ld.Owner.Email);//sending message via Email to the Owner of the lead
      mail.setToAddresses(sendTo);
      mail.saveAsActivity = false;
      mail.setTemplateId(Template);//Using custom setting field template as template id
       mail.setTargetObjectId(ld.Ownerid);                           
      mails.add(mail);
  Messaging.sendEmail(mails);
}
}
}

Thanks
​Raj.
Hi All,

Add/Remove Records using LWC.

If any one want to create Add/Remove multiple records in lightning web component dynamically then please refer this post. 

Features:
1. Add rows using plus( + ) button.
2. Dynamic Add/Remove record row.
3. Proper Serial Number in table. For each index starts from 1.
4. Clear All Feature.
5. Save button label change button.
6. Toast Message after record succesfully inserted.

Refer the code in below post...

Like this Post if it's helps to any one !!!

Thanks,
Maharajan.C
Hi Friends,

Is there any way to retrieve my SF Dev Org Because i lost my Org Due to the Authenticator App in my Mobile i.e, am uninstalled the Authenticator App in my Phone which have a link with my Dev Org.

Thanks,
Raj.
I need help writing a test class for my apex code. I really don't know much about apex. But I was able to create a visualforce page and an apex class that extends the standard controller. Everything works perfectly in my sandbox. But I have no idea how to write the test class so that I can push my code into production.

Here is my code for the visualforce page:

<apex:page standardController="WorkOrder" extensions="WorkOrderLineItemsOnWorkOrderClass">     

    <apex:sectionHeader title="Equipment on quote number {! WorkOrder.Workorder_Name__c } for {! WorkOrder.Account.Name }"/>
  
    <p></p>
    
    <apex:pageblock id="WorkOrderLineItemList"> 

         <br/> 

            <apex:pageBlockTable value="{!WorkOrderLineItems}" var="item">                          

                <apex:column value="{!item.Product_Code_Display__c}"/>
                
                <apex:column value="{!item.Description}"/> 
                
                <apex:column value="{!item.Quote_Line_Quantity_Display__c}"/>
                
                <apex:column value="{!item.Quote_Line_Net_Total_Display__c}"/> 
                
                <apex:column value="{!item.Group_Name__c}"/>
               
            </apex:pageBlockTable>     
            
     </apex:pageblock> 

</apex:page>

And here my code for my apex class that extends the standard controller:

public class WorkOrderLineItemsOnWorkOrderClass {

    public List<WorkOrderLineItem> WorkOrderLineItems{get;set;}

    public WorkOrder WorkOrders {get;set;} 

    public WorkOrder wo {get;set;} 

     //Constructor 

    public WorkOrderLineItemsOnWorkOrderClass(ApexPages.StandardController controller) { 

        wo = (WorkOrder)controller.getRecord();      

        WorkOrders = [SELECT id FROM WorkOrder WHERE id=: wo.id LIMIT 1]; 

        WorkOrderLineItems = [SELECT id,Group_Name__c,Product_Code_Display__c,Quote_Line_Quantity_Display__c, Description, Quote_Line_Net_Total_Display__c FROM WorkOrderLineItem WHERE WorkOrderid = :WorkOrders.id ORDER BY Quote_Line__c];     


   
}
 
trigger contactTrigger on Contact (after insert,after update) {
List<Id> ids = new List<Id>();
    for(Contact con: trigger.new){
        ids.add(con.AccountId);
    }
    List<Account> aList= [select id,name, Task__c, (select id,Task__c from contacts) from account where id IN: ids];
        
    
    for(Account acc: aList){
        for(Contact con: acc.contacts){
            system.debug('task'+con.Task__C+acc.Task__C);
        if(con.Task__C=='Submitted'){
            acc.Task__C='Achieved';
            } system.debug('task'+con.Task__C+acc.Task__C+acc.Name);
        }
    }
}
    
    
    
    
    
    
    
    
 
Hi All,

The following tag is executing as per requirement:
 
List<integer> list1= new List<integer>();
list1.add(10);
list1.add(20);
list1.add(30);
list1.add(40);
system.debug('Value of List after increase is '+list1);

However if I use the list.add(index,element) method to add elements I am receivng error System.ListException: List index out of bounds: 0

The code I am having error with is
 
List<integer> list1= new List<integer>();
list1.add(0,10);
list1.add(1,20);
list1.add(2,30);
list1.add(3,40);
system.debug('Value of List after increase is '+list1);
Please advise.

Thanks!!
 
I have one query-
 Component-
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="feedbackCls">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="feedbackLst" type="object"/>
    <div>
        <table>
            <thead>
                <th>Opportunity Name</th>
                <th>Manager</th>
                <th>Comments</th>
                <th>Action</th> 
            </thead>
            <tbody>
                <aura:iteration items="{!v.feedbackLst}" var="lst">
                    <tr>
                        <td>{!lst.Opportunity__r.Name}</td>
                        <td>{!lst.Opportunity__r.ownerId}</td>
                        <td>{!lst.Feedback__c}</td> 
                        <td><input id="{!lst.Id}" type="button" label="approve" value="Approve" onclick="{!c.doApprove}"/><input type="button" value="Reject"/></td>
                    </tr> 
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>

Controller - 

({
    doInit : function(component, event, helper) {
        console.log('===Test==');
        var action = component.get("c.fetchRecords");
        console.log('===action==='+action);
        action.setCallback(this, function(response) {
            console.log('===response==='+response.getReturnValue());
            component.set("v.feedbackLst",response.getReturnValue());
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log("From server: " + response.getReturnValue());
            }
        }); 
        $A.enqueueAction(action);
    },
   doApprove:function(component,event,helper){
        var a = event.target.Id;
        console.log(a);
  },
})

Apex class-
 
public class feedbackCls {
    @auraEUser-added imagenabled
    public static list<Feedbacks__c> fetchRecords(){
        list<Feedbacks__c> lst = new list<Feedbacks__c>();
        lst = [select id,name,Feedback__c,Opportunity__r.Name,Opportunity__r.ownerId from Feedbacks__c];
        return lst;
    }
Hi All,

I am having trouble with the below code:
 
Public Class SOQLTry{
    
    public static void showAccountsBasedOnRating(String AccountRating){
        
        List<Account> List2 = [SELECT Name, Rating
                               FROM Account
                               WHERE Rating IN (:AccountRating)];
            
        For(Account AAR : List2) {
            system.debug('Name of Account with Rating ' +AAR.Rating+' is '+AAR.Name );
        }
    }
    
    
    public static void showIndustryOfAccounts(String AccountIndustry){
        List<Account> List3 = [SELECT Name, Industry
                               FROM Account
                               WHERE Industry = :AccountIndustry];
        for(Account AAI : List3)
        	{
            IF(List3.isEmpty()==False)
            {
            system.debug(AAI.Name+' belongs to the '+AAI.Industry+' Industry');
            }
            
            ELSE 
            {
                system.debug('There is no account related to ');
            }
        }
    }
}

The showAccountsBasedOnRating() method is executing as per expectations.

The showIndustryOfAccounts() method is executing with upto "IF" command but the ELSE commoand is not executing.

Any idea what could be causing this.

Thanks.
 
I found this How To Show HTML Email Right On Your Case Page (http://success.salesforce.com/ideaView?id=087300000007TOe) that really works great for what we want but cannot understand how to test it.
 
public with sharing class CaseHTMLEmailController {
    private final Case caseObj;

    public String firstHTMLEmail { get
        {return getFirstHTMLEmail(); }
    }
    
    public CaseHTMLEmailController(ApexPages.StandardController stdController) {
        this.caseObj = (Case)stdController.getRecord();
    }

    public String getFirstHTMLEmail() {
        EmailMessage firstEmail = [Select HtmlBody From EmailMessage where ParentId=:caseObj.Id order by LastModifiedDate asc limit 1];
        if (firstEmail!=null) {
            return firstEmail.HtmlBody;
        }
        
        return '';
    }
}

I need the email-to-case context where the case was generated by an email and test  it pulling the data from emailMessage for this visualforce page.
How can I store this on a picklist.

is my attribute correct?
<aura:attribute name="Type" type="String" />

this is my apex class to return list
@AuraEnabled
    
    public static List<String> getAuthorized(string recordId){
        List<ID> coid = new List<ID>();
        
        List<String> MemName = new List<String>();
        for( Member__c covmem :  [SELECT Id,Name, FROM Member__c WHERE Account__c =: recordId ] )
        {
            coid.add(covmem.Personel__c);  
        }
        for(Personel__c cov : [SELECT Id,Name FROM Personel__c WHERE Id =: coid ]){
            
            MemName.add(cov.Name);
        }
        return MemName;
    }

this is my helper
getAuthorized : function(component,event,helper){
        var recordId = component.get("v.recordId");
        var action = component.get("c.getAuthorized");
        action.setParams({recordId : recordId});
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
               //alert(JSON.stringify(response.getReturnValue()));
                 var coidpicklist = response.getReturnValue();
 				component.set("v.Type",coidpicklist);
                //var coidpicklist = response.getReturnValue()[0].ValuePicklist__c;
            }
        });
        $A.enqueueAction(action);
    },


 
Hello,

I have a map with Name(String) and Ranks(Integer),
Name is the Pricebook name and Rank is Order by.
map<String,Integer> mapOfNameAndRank = new map<String,Integer>();

Name1, 1
Name2, 2
Name3, 3
I am populating SelectOption in below manner: 
public list<SelectOption> listOfOpt {get;set;}
for(priceBook2 prc : [select id,Name from priceBook2 ){
            listOfOpt.add(new SelectOption(prc.Id,prc.Name));
        }

My usecase is that, the SelectOption should display the Name is the order defined in map.

How can i reiterate the SelectOption inorder to order it.

thank you for suggestion
Hello!

I have been using Salesforce for a couple of years now, but I am starting to dip my toes in Apex.  In the past we have utalized offshore resources, but to make a long story short we don't want to soely rely on them for coding and instead call them for larger projects.  I've found where the new condition needs to be added, but I'm not 100% sure what needs to be done.  Basically, I want to say "if custom checkbox = true, dont update the owner field".  Could I please have some help adding the new condition?

Thanks a bunch!

Here is the current code block:
//Set the Order Owner with Order Sales Rep
    public static void UpdateOrderOwner(list<Order> listNew, map<id,Order> mapOld){
        RTT_Setting__mdt DefOwnSett = [SELECT Id, DeveloperName, Value__c FROM 
                                       RTT_Setting__mdt where DeveloperName='Default_Residential_Order_Owner' limit 1];
        
        for(Order rec: listNew ){
            if(rec.RecordTypeId==vResOrderRecTypeId){
                if(mapOld.isEmpty() ||rec.Primary_Sales_Rep__c <> mapOld.get(rec.Id).Primary_Sales_Rep__c){
                    if(rec.Primary_Sales_Rep__c == null ){
                        rec.OwnerId=DefOwnSett.value__c;
                    }
                    else {
                        rec.OwnerId=rec.Primary_Sales_Rep__c;
                    }
                }
            }
trigger OpportunityBackup on Opportunity (after update) 
{

      List<My_Backup__c> lstToInsrt = new List<My_Backup__c>();      
    for(Opportunity op1 : Trigger.new)
    {
         if(trigger.oldMap.get(op1.Id).Name !=op1.Name)
         {
             My_Backup__c backup = new My_Backup__c();
             backup.Name = trigger.oldMap.get(op1.AccountId).Name;
             lstToInsrt.add(backup);
         }
    }
    if(lstToInsrt.size()>0)
    {
        update lstToInsrt;
    }
    
}
I have a string in apex controller stored as follows: String qtr={"Forecast_Category__c":["Unqualified","Not addressable"],"StageName":["1. Understand Customer","2. Discover Needs"]}. 
is it possible to store the following in the below format?
{Forecast_Category__c:[Unqualified,Not addressable] StageName:[1. Understand Customer,2. Discover Needs]}. 
Params1:
public class params1 {
    @AuraEnabled
    public static List<Account> accountthod(){
        List<Account> accounts=[select id,name,industry,rating,phone from Account limit 4];
        return accounts;
    }
}

pasasm.cmp
<aura:component controller="params1">
    <aura:attribute name="acclist" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.invoke}"/>
    <aura:iteration items="{!v.acclist}" var="a">
        <p>{!a.name} &nbsp;&nbsp;&nbsp;{!a.industry} &nbsp;&nbsp;&nbsp;{!a.rating} &nbsp;&nbsp;&nbsp;{!a.phone}</p>
    </aura:iteration>
</aura:component>

parasmController.js
({
    invoke : function(component, event, helper) {
        var action=component.get("v.accountthod");
        action.setCallback(this,function(response){
            console.log("invoked");
            var state=response.getState();
            if(state==='SUCCESS'){
                console.log('Operation successfull');
                component.set("v.acclist",response.getReturnValue());
            }else{
                console.log('Operation failed');
            }            
        });
        $A.enqueueAction(action);
    }
})

parasmap.app
<aura:application extends="force:slds">
    <c:parasm />
</aura:application>
Hi ..
i am trying to write Validation rules, but its conflits..can you pls help some one on this.
can someone pls check and let me know whats wrong here ...or if you have any better pls update

 AND
        (
        OR((Contract_Year_End_Date__c > Effective_Date__c),First_Year_Indicator__c = FALSE), 
        ISCHANGED(Contract_Year_End_Date__c )
        )              
    Error Message :
Cant update Contract Year End Date when first Year Indicator checkbox is False 
     AND
     Contract year end date should be less than Effective Date     
Note : its working as expected.

2)        
AND(
OR(
ISPICKVAL(Contract_type__c,"test1"),
ISPICKVAL(Contract_type__c,"test2")
),
First_Year_Indicator__c = TRUE),
ISCHANGED(Contract_Year_End_Date__c)
)
Error Message :
Contract Year End Date Cant be Edited , When First Year Contract Year checkbox is Checked And contract type picklist is test1 Or test2        
        
        Note : Here i am getting conflits ....displaying first VR Message not display this VR Message and also its not matching my requirment 
        
Thanks
RK
  • April 26, 2020
  • Like
  • 0
I am trying to get the Contact Name and Email of the Primary Opportunity Contact. I am having difficulty as what is being returned is the Id of the contact and no email. 

Could someone let me know what key piece I'm missing here? 
 
List<OpportunityContactRole> primaryContactInfo = [SELECT OpportunityId, Contact.Name, Contact.Email
                    FROM OpportunityContactRole
                    WHERE OpportunityId ='0063h00000551YKAAY' AND isPrimary = TRUE];

System.debug(primaryContactInfo[0].get((string)'OpportunityId'));
System.debug(primaryContactInfo[0].get((String)'ContactId'));

How would I expose Contact.Name and Contact.Email? 
Hi everyone, 

I'm writing a handler class called via a before insert trigger to prevent leads from getting created if they have a matching email across standard objects (account, contact, and lead). When I test my code in the anonymous window, I'm using an email that is planted across the three objects. Although my end goal is to prevent the creation of a lead if a matching email is found, I'm having trouble even seeing results in the debug log of parameters passed into my System methods. It would be super helpful if a member of this community can review my code and let me know where you think there are any holes and why it may be that my trigger and class aren't working properly. Thank you in advance! 
trigger MasterLeadTrigger on Lead (before insert, before update, before
    delete, after insert, after update, after delete,  after undelete) {
        
        List<Lead> newList = Trigger.new;
        
        MasterLeadTriggerHandler handler = new MasterLeadTriggerHandler();
        
		if(Trigger.isInsert && Trigger.isBefore){
            handler.OnBeforeInsert(Trigger.new);
        }
}

public class MasterLeadTriggerHandler {
    public void OnBeforeInsert(List<Lead> listNew){
        if(listNew.isEmpty()){
            System.debug('List is empty');
        }else{
            System.debug(listNew.size());
        }
        Set<String> email = new Set<String>();
        for(Lead newLead : listNew){
            if(newLead.Email != null){
                email.add(newLead.Email);
                System.assertEquals(email.size(),1);
            }
        }
        List<Lead> dupeLead = [SELECT Id FROM Lead WHERE Email IN :email 
                              OR Secondary_Email__c IN :email
                              OR Additional_Email__c IN :email];
        for(Lead newLead : listNew){
            if(dupeLead.size()>0){
                newLead.addError('This is a duplicate: '+dupeLead[0].Id);
            } update newLead;
        }
	}
}

 
Can't do with Workflow or Process Builder...can I do this with a Trigger? New to Triggers

Trying to update a custom field (Call_Copy_Last_Reported_Date__c) on User object with a date (Week_Ending__c) from custom object (Call_Copy_Reporting__c) when a new Call Copy Report is created. 

Custom Object - Call Copy Reporting
Owner (Lookup)
Week_Ending__c (Date)

User Object
Call_Copy_Last_Reported_Date__c (Date)

Any help would be appreciated!
Hi, i write a code about datatable and apex, but  the result is null.
I have a custome object called Warehouse.It have a relationship field, related to Product object. And a number filed called Amount.
 want to show they in datatable. Now page show null but amount of records is right. And i try to show Name,Type__c , they will show. Just Product__r.Name and Amount__c is null.
Im sure that my SOQL is right.because i run it in develope consle query editor.

This is my code.
cmp:
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
	<aura:attribute name="columns" type="List"/>
	<aura:attribute name="data" type="Object"/>
	<aura:attribute name="errors" type="Object" default="[]"/>

	<lightning:card title="Pending QA">
		<lightning:datatable
			columns="{! v.columns }"
			data="{! v.data }"
			keyField="Id"
			errors="{! v.errors}"
			hideCheckboxColumn="true"/>
	</lightning:card>
controller:
doInit : function(component, event, helper) {
    	component.set('v.columns', [
            { label: 'Product', fieldName: 'Product__r.Name', type: 'text',editable:false},
            { label: 'Amount', fieldName: 'Amount__c', type: 'text',editable:false}]);
    	helper.getPendingRecord(component,event,helper);
    }
Helper:
getPendingRecord : function(component, event, helper) {
		var action = component.get("c.query");
        // call back
        action.setCallback(this, function(response){
            var state = response.getState();
            // call back success
            if (state == "SUCCESS"){
                var result = response.getReturnValue();
                component.set('v.data', result);
            }
            // call back failed
            else {
                var toastEvent=$A.get("e.force:showToast");
                toastEvent.setParams({
                    "title":'Error!',
                    "message":'Get Record Failed!',
                    "duration":5000,
                    "type":ERROR
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);
	}
class:
public static List<Warehouse__c> query() {
    	List<Warehouse__c> pending = new List<Warehouse__c>();
        pending = [SELECT Product__r.Name,Amount__c FROM Warehouse__c WHERE Type__c = 'pendingArea'];
        return pending;
    }
Pls help me. Thanks!


 
I'm getting the following error when attempting to created this custom formula field on the Opportunity object:

LMS Opportunity Owner Auto-Poulate = 
IF(
INCLUDES(Products_of_interest__c, "Learning Management System (LMS)"),
INCLUDES(Products_of_interest__c, "Schoology LMS"), 
Account.LMS_Account_Owner__c)

Conditions are to set the LMS Opportunity Owner to the LMS Account Owner if Opprotunity Products of Interest = Learning Management System (LMS) or Schoology LMS.

The formula above is giving me the following error:  Incorrect parameter type for function 'IF()'. Expected Boolean, received Lookup(User)

What am I doing wrong?
I'm getting the following error when attempting to created this custom formula field on the Opportunity object:

LMS Opportunity Owner Auto-Poulate = 
IF(
INCLUDES(Products_of_interest__c, "Learning Management System (LMS)"),
INCLUDES(Products_of_interest__c, "Schoology LMS"), 
Account.LMS_Account_Owner__c)

Conditions are to set the LMS Opportunity Owner to the LMS Account Owner if Opprotunity Products of Interest = Learning Management System (LMS) or Schoology LMS.

The formula above is giving me the following error:  Incorrect parameter type for function 'IF()'. Expected Boolean, received Lookup(User)

What am I doing wrong?

Hi, folks!

Could you please help me with the following scenario?

I have created a <lightning-datatable> tag in my <template> and I need to hidden the dropdown list with the options Wrap Text and Clip Text.

Screenshot:

As far as I know, there isn't any OOTB class that could help me with that.

When trying to apply a custom style, nothing happens:

.THIS slds-button slds-button_icon-baree{
    display: none ;
}

Has anyone any idea of how to solve that?

Thanks in advance.

 

Hello,

Did anyone else notice that the view state limit in Visualforce pages has been increased from 135 to 170 KB in the new release of Spring 2019