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


  • Chatter
    Feed
  • 278
    Best Answers
  • 1
    Likes Received
  • 3
    Likes Given
  • 13
    Questions
  • 990
    Replies
Hi! I am new with SF Apex programming, then I am stuck with a simple problem I think so.
After I added a Validation Rule to unable the user saves a new account without entering data in the fields (ShippingCity, ShippingPostalCode, ShippingStreet) I am facing some problems with a trigger test class.

I must be able to put fake values in my trigger test for these new fields that now are required field.

Could you help me, pls?
 
@isTest
    static void UpdateAccountProspect1() {        
        Boolean result = true;
        try{
            User testUser = SetupClassTest.createUserSalesRep('2801','testadmin@testorg.com', 'testadmin@testorg.com.prod');
            System.runAs(testUser){
                RecordTypeInfo rt = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Prospect_2801');
                List<Account> accToUpdate = SetupClassTest.generateNAccountsWithRT(1, rt.getRecordTypeId(), '2801');
                accToUpdate[0].RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Customer_2801').getRecordTypeId();
                update accToUpdate[0];
            }
        }catch(Exception e){
            System.debug('Línea: ' + e.getStackTraceString());
            result = false;
        }
        System.assert(result);
    }



 
Hi all,
I have working Code the sends an SMS  via Apex and Twilio, Great stuff. The trouble I am having is writing the Tests and I just need a little help. I don't do near enough Apex for my liking and I am feeling it here. 

IAny help/pointers would be most appreciated. 

Apex class:
public with sharing class Twilio {
    
    Public string text1 {get;set;}
    public boolean showmessage{get;set;}
    public string selectedvalue {get;set;} 
    
    private final contact acct;
    public Twilio(){}
    public Twilio(ApexPages.StandardController stdController) {
        this.acct = (contact)stdController.getRecord();       
    }
    
    Public static Void sendfromtwilio (string Fromnumber,string text,string tonumber) {
        
        errorResponseWrapper erw;
        configuration_setting__c cstt=new configuration_setting__c();
        cstt = [select Name,AccountSid__c, Active__c,AuthToken__c,Bulk_SMS__c,Contact_Phone_Number__c,Lead_Phone_Number__c,TestPhone__c FROM configuration_setting__c where Name='Twilio' limit 1];
        String account = cstt.AccountSid__c;
        String token = cstt.AuthToken__c;
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+account+'/SMS/Messages.json');
        
        req.setMethod('POST');
        
        String VERSION  = '3.2.0';
        
        req.setHeader('X-Twilio-Client', 'salesforce-' + VERSION);
        
        req.setHeader('User-Agent', 'twilio-salesforce/' + VERSION);
        
        req.setHeader('Accept', 'application/json');
        
        req.setHeader('Accept-Charset', 'utf-8');
        
        req.setHeader('Authorization','Basic '+EncodingUtil.base64Encode(Blob.valueOf(account+':' +token)));
        
        req.setBody('To='+EncodingUtil.urlEncode(+tonumber,'UTF-8')+'&From='+EncodingUtil.urlEncode(+Fromnumber,'UTF-8')+'&Body='+text);
        
        Http http = new Http();        
        HTTPResponse res = http.send(req);  
        System.debug(res.getBody());
        system.debug(res.getStatusCode());
        if(res.getStatusCode()==201)
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm,'SMS Sent Successfully'));
        } else{
            erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,erw.message));
            System.debug('ERROR');
        }
    }
    public PageReference ok(){
        PageReference acctPage = new PageReference('/' +acct.Id);
        acctPage.setRedirect(true);
        return acctPage;
    }  
    public class errorResponseWrapper{
        String code;       
        String message;        
        String moreInfo;        
        String status;    
    }
}
  • January 14, 2020
  • Like
  • 0
Hi All, 

I am facing issue of our test class we only got 13 perent code coverage please help
me

trigger autoCreateContactController on Case (before insert) {
    
    for(Trigger_Control__c tc:Trigger_Control__c.getAll().values())
    {
        if( tc.Enable_Auto_Create_contact_Trigger__c==true)
        {
            
              for(case cs:trigger.new)
       {
          
           if(userinfo.getName()=='Automated Workflow'){   
               contact[] lstcontact= [select id from contact where email=:cs.SuppliedEmail limit 1];
               
                    if(!lstcontact.isEmpty()) 
                   {
                  String contId=lstcontact[0].id;
                    if(contId!=null)
                    {
                    cs.ContactId=contId;
                    }
                } 
                else { 
                   
                    String leftPart = cs.Suppliedname;
                    String[] leftPartSplitted = leftPart.split('\\s+');
                    if(leftPart!=null || leftPart!='') 
                    {
                        if(leftPartSplitted.size() == 3)
                        {
                            String firstName = leftPartSplitted[0]; 
                            String lastName = leftPartSplitted[1]; 
                            String middlename=leftPartSplitted[2]; 
                            contact con1 =new contact(); 
                            con1.firstname=firstName;
                            con1.LastName=lastName+middlename;
                            con1.Email=cs.SuppliedEmail;
                            con1.AccountId='0010W00002MuDcQQAV';
                            insert con1; 
                            cs.ContactId=con1.Id; 
                        }  
                        else if(leftPartSplitted.size() == 2) 
                        { 
                            String firstName = leftPartSplitted[0];
                            String lastName = leftPartSplitted[1]; 
                            contact con1 =new contact();
                            con1.firstname=firstName; 
                            con1.LastName=lastName;  
                            con1.Email=cs.SuppliedEmail;  
                            con1.AccountId='0010W00002MuDcQQAV';  
                            insert con1;   
                            cs.ContactId=con1.Id; 
                        }
                        else if(leftPartSplitted.size() == 1)
                        { 
                            String lastName = leftPartSplitted[0]; 
                            contact con1 =new contact();
                            con1.LastName=lastName;
                            con1.Email=cs.SuppliedEmail;
                            con1.AccountId='0010W00002MuDcQQAV';
                            insert con1; 
                            cs.ContactId=con1.Id;    
                }
            }
                               
                    
               } 
               }}}
            
    }}


My test class is 

@isTest
public class AutoCreateContactControllerTest {

@isTest
    public Static void SpamTestmethod()
    {  Account acc = new Account(Name='MassBay');
        insert acc;
        
        Contact con = new Contact(AccountId=acc.Id,LastName='test',Email='tttt@test.com');
        insert con;
        Trigger_Control__c tc=new Trigger_Control__c();
        tc.Enable_Auto_Create_contact_Trigger__c=true;
        tc.Name='test tc';
        insert tc;
     
     List<case>lstcase=new List<case>();
          
       
            List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'MassBayCC_Ticket'];
            Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
      
        cs.Subject='tesr';
        cs.Description='Test description';
         cs.SuppliedEmail='tttt@test.com';
        cs.SuppliedName='hello world';
          lstcase.add(cs);
          Case cs1 = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
        
        cs1.Subject='tesr';
        cs1.Description='Test Description';
        cs1.SuppliedEmail='tttt@test.com';
        
        
        
        cs1.SuppliedName='hello world world';
          lstcase.add(cs1);
          Case cs2 = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
        cs2.Subject='tesr';
        cs2.Description='Test Description';
        cs2.SuppliedEmail='tttt@test.com';
        cs2.SuppliedName='hello';
        lstcase.add(cs2);
          insert lstcase;
        
       
    }
}
Hello, I am an admin adventuring into learning code and I cannot figure out why the following Lightning Web Component is not working. (I've left out some of the code for simplicity.) Thank you!

HTML:
<p>Total Licenses:<span class="slds-p-horizontal_small">{totalPartnerLicenses}</span></p>

JS:
import { LightningElement, track, wire } from 'lwc';
import queryTotalPartnerLicenses from '@salesforce/apex/queryForLicenses.queryTotalPartnerLicenses';
export default class PartnerCommunityLicenses extends LightningElement {
@track totalPartnerLicenses = 7;
@wire(queryTotalPartnerLicenses) totalPartnerLicenses;
}

APEX CLASS:
public with sharing class queryForLicenses {
@AuraEnabled(cacheable=true)
public static Integer queryTotalPartnerLicenses(){
List<UserLicense> totalPL = [SELECT ID, TotalLicenses FROM UserLicense WHERE Name = 'Partner Community'];
UserLicense pl = new UserLicense();
Integer numTotalLicenses;

if(totalPl.size()>0){
pl = totalPL[0];
numTotalLicenses = Integer.valueOf(pl.TotalLicenses);
}
else {
numTotalLicenses=0;
}
return numTotalLicenses;
}
}
Hi all,
I have a requirement of showing small icon beside records in datatable 
I am adding a picture for reference
User-added imagehow to do this?

thanks in advance
Hello Everyone,

I had an issue with Commandbutton which I need to redirect the page from the Visualforce page to some other company Website Contact Us page.

Here is my CommandButton code and Controller class code.

VF Page CommandButton:

 <apex:commandButton style="color:white; background-color:red; background-image:none; width:150px; height:35px" action="{!Cancel}" value="Cancel"  />

Controller Class:

 public PageReference Cancel(){
        PageReference pr = new PageReference('/www.bren.com/residential/contact');
        pr.setRedirect(true);
        return pr;
    }


Please help me with this issue.

Thanks and Regards,
Azar Khasim.
I've created this VR that will prevent a user from entering a value over 100. Is it possible to add to the syntax that would also not allow a user to enter a value of less than 20%? 
 
Percent_Value__c  > 1

 
  • December 11, 2019
  • Like
  • 0
Hi All,
   I am new to Salesforce and i tried test class for below trigger but i got code coverage only 35%.

whenever An Account is created with number_of_Employees__c(custom field)>99 create 10 opportunities for Account.

trigger CreateTenOpportunity on Account (after insert)
{
    List<Opportunity> oppList=new List<Opportunity>();
    for(Account acc:trigger.new)
    {
        if(acc.Number_of_Employees__c>99)
        {
            for(integer i=0;i<10;i++)
            {
              opportunity opp=new opportunity();
              opp.Name=acc.Name+ i;
              opp.AccountId=acc.Id;
              opp.StageName='Prospecting';
              opp.CloseDate=Date.today()+15;
              oppList.add(opp);  
            }
        }
    }
    if(oppList.size()!=0){
        insert oppList;
    }
}

 
Even i changes name field ,update trigger is getting called and adding un-neccessary discount to price.Expected is that it should update only if brand is getting change.How can i remove this ?


trigger MobileShopeeDiscount on Mobile__c (before insert,before Update) {
    if(trigger.isInsert == true ){
        MobileShopeeDiscount.MobileShopeeDiscountFuncation(Trigger.new);
    }
       if(trigger.isUpdate == true){
       MobileShopeeDiscount.OldCustomerDiscountFuncation(Trigger.new);
    }

}

public class MobileShopeeDiscount {

    public static void MobileShopeeDiscountFuncation(list<mobile__c>VarList){
        for(mobile__c tempvar :VarList){
            if(tempvar.Brand__c == 'samsung'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.1);
                tempvar.DiscountStatus__c = 'Congrates !! You got 10% Discount';
            }else if(tempvar.Brand__c == 'Apple'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.2);
                tempvar.DiscountStatus__c = 'Congrates !! You got 20% Discount';
            }
        }
    }

public static void OldCustomerDiscountFuncation(list<mobile__c>VarList1){
        for(Mobile__c tempvar :VarList1 ){
            if(tempvar.Brand__c == 'samsung'){
                tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.05);
                tempvar.DiscountStatus__c = 'Congrates !! You got 5% Discount';
            }else if(tempvar.Brand__c == 'Apple'){
               // tempvar.Price__c = tempvar.Price__c-(tempvar.Price__c *0.2);
                tempvar.DiscountStatus__c = 'No Discount Applicable on this purchase';
            }
        }
        
    }


}
This component redirects a community user to the user's Account Detail page in a community. How would I change the code to redirect to a custom object (Billing__c) Detail page? I've tried changing the recordId path to LoggedInUser.Contact.AccountId.Billing__c with no luck. My path might be wrong. I am not a developer so any advice would be greatly appreciated.
({
    redirectToAccount: function(component, event, helper) {
        var loggedInUser;
        var state;
        var navEvt;
        
        var action = component.get("c.getLoggedInUser");
        action.setCallback(this, function(response) {
            state = response.getState();
            if (state === "SUCCESS") {
                loggedInUser = response.getReturnValue();
                navEvt = $A.get("e.force:navigateToSObject");
                navEvt.setParams({
                    "recordId": loggedInUser.Contact.AccountId,
                    "slideDevName": "detail"
                });
                navEvt.fire();
            }
        });
        $A.enqueueAction(action);
    }
})

 
Please help me to increase the code coverage of this class. actually is is only at 25%. the class is to increment in field each time a visualforce page called "DeliveryPage" is launched.  This field is on an object called Delivery__c which is a child of Account
public class DeliveryPageClass {
   // public Delivery__c delivery{get;set;}
public id deliveryId;
    public DeliveryPageClass(ApexPages.StandardController stdController)
    {
        deliveryId=stdController.getId();
     
    }
    public void updateDelivery()
    {
        Delivery__c delivery = [select id,Print_Counter__c from Delivery__c where id=:deliveryId];
        if(delivery.Print_Counter__c==null)
        {
            delivery.Print_Counter__c=1;
        }
        else
        {
            delivery.Print_Counter__c=delivery.Print_Counter__c+1;
        }
        system.debug(delivery);
        update delivery;
        system.debug(delivery);
        
    }

}

Test Class
@isTest
public class DeliveryPageClassTest {
    static testMethod void TestDeliveryPageClass(){
     Account pa = new Account(Name ='test Account parent', Representant__c ='hkjlhjd', 
     Distribution_Center__c='CRD Cayes', Class__c = 'Clinic', Type = 'CLINICS', 
     Departement__c = 'NORD', Address__c ='Test Address');
     insert pa;
         
 Account a = new Account();
 a.Name ='test Account'; 
 a.Representant__c ='Bijou';
 a.Distribution_Center__c='FFP Caracole';
 a.Class__c = 'NGO'; 
 a.Type = 'CLINICS';
 a.Departement__c = 'NORD';
 a.Address__c ='Test Address';
 a.ParentId = pa.ID;
 insert a ;
    
        Delivery__c del = new Delivery__c();
        del.Beneficiaire__c = a.Id;
        del.Ration__c =3;
        del.Delivery_status__c='Pending';
        
        insert del;
          
       
        ApexPages.StandardController sc = new ApexPages.standardController(new Delivery__c());
        DeliveryPageClass dpc = new DeliveryPageClass(sc);
    }
}
 
 
Here It is my code:- 
==========Apex Controller===================
public class DropdownContrl {
     @AuraEnabled
    Public static String accountId{get;set;}
   
     @Auraenabled
  public static List<Account> getAccounts()
  {
      List<Account> accList = new List<Account>();
      accList = [SELECT Id, Name FROM Account];
      system.debug('Accounts '+accList);
            return accList;
  }
      @Auraenabled
     public static List<Contact> getContact(List<Id> accountIds)
  {
      System.debug('Acclount Id '+accountIds);
      List<Contact> conlst = new List<Contact>();
      conlst = [SELECT  FirstName, LastName,Email,Phone from Contact WHERE 
                                    accountId in : accountIds];
      system.debug('contacts '+conlst);
            return conlst;
  }
    }

=========Component=========
<aura:component controller="DropdownContrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
    <aura:attribute name="Accounts" type="List" />
    <aura:attribute name="Contacts" type="List" />
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    <h2 class="slds-page-header__title">Display Account List</h2>
    <lightning:layout>
        <article class="slds-card slds-m-bottom_medium">
            <div class="slds-media__body">
                <div>
                    <lightning:layoutitem>
                        <lightning:select aura:id="act" name="selectAccount" >
                            <option value="" label="--None--">
                            </option>
                            <aura:iteration items="{!v.Accounts}" var="item" >
                                <option value="{!item.Id}" label="{!item.Name}" >
                                    {!item.Name}
                                </option>
                            </aura:iteration>
                        </lightning:select>
                    </lightning:layoutitem>
                </div>
            </div>
        </article>
    </lightning:layout>
    <div>
            <lightning:button label="Get Contacts" title="Neutral action" onclick="{! c.getcontacts }"/>

                <!--     <button  class="slds-button slds-button_brand" style="height:30px;width: 50px;" label ="Get Contacts" onclick="{!c.getcontacts}" ></button>-->

    </div>
     <h2 class="slds-page-header__title">Related Contacts</h2>
     <div  aura:id="ContactRecordViewController" class="slds"> 
        <table class="slds-table slds-table--bordered slds-table--striped">
            <thead>
                <tr>
                    <th scope="col"><span class="slds-truncate">First Name</span></th>
                    <th scope="col"><span class="slds-truncate">Last Name</span></th>
                    <th scope="col"><span class="slds-truncate">Email</span></th>
                    <th scope="col"><span class="slds-truncate">Phone</span></th>
                 
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.Contacts}" var="con" indexVar="index">
                    <tr>
                        <td data-index="{!index}">{!con.FirstName}</td>
                        <td data-index="{!index}">{!con.LastName}</td>
                        <td data-index="{!index}">{!con.Email}</td>
                        <td data-index="{!index}">{!con.Phone}</td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>
=============Helper==============
({
    fetchContacts : function(component, event, helper) {
        var action = component.get("c.getContact");
        console.log(action);
        var accountId = component.get("v.recordId");
        console.log(accountId);   
        action.setParams({
            accountIds: accountId
        });
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS') {
                var contactList = response.getReturnValue();
                component.set("v.Contacts",contactList);
                console.log(contactList);
            }
            else {
                alert('Error in getting data');
            }
        });
        $A.enqueueAction(action);
    },

})

=====================Js controller============

({
doinit : function(component, event, helper) {
    console.log('load');
    var action = component.get('c.getAccounts');
    action.setCallback(this, function(response){
            var result =response.getReturnValue();
            console.log(result);
            component.set("v.Accounts",result);
            console.log(result);
    });
    $A.enqueueAction(action);
},
     getcontacts : function(component, event, helper) 
    {
        
        helper.fetchContacts(component, event, helper);
    } ,
})
Hello,

I'm trying to display a message error on the lightning component when I get some error on my apex class, like when I call apex and delete account and Customeobject__c but one of them is not deleted and  response will be ''Success"

Please, can anyone could help me?
Here It is my code:-
======Apex Controller========
public with sharing class AccountController1_picklistrendering { public String account { get; set; } public String selectedAccId{get;set;} public String selectedConId{get;set;} public List<SelectOption> getAccountNames() { List<SelectOption> accOptions= new List<SelectOption>(); accOptions.add( new SelectOption('','--Select--')); for( Account acc : [select Id,name from Account ] ) { accOptions.add( new SelectOption(acc.Id,acc.name)); } return accOptions; } public List<SelectContact> getContactNames() { System.debug('Entered ContactNames account id...........'+selectedAccId ); if(selectContact != null) contact con = [select name from contact where accountid=:selectedAccId ]; return con; } }


=============VF Page==================
<apex:page controller="AccountController1_picklistrendering"> <apex:form > <apex:pageBlock title="Account Name"> Account Names&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <apex:selectList value="{!selectedAccId}" size="1"> <apex:selectOptions value="{!AccountNames}"/> <apex:actionSupport event="onchange" reRender="a"/> </apex:selectList> <br/><br/> Related Contact Names&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <apex:pageBlockTable value="{!ContactNames}" var="items"> <apex:column value="{!items.name}"/> </apex:pageBlockTable> <apex:selectList value="{!selectedConId}" size="1" id="a"> <apex:selectOptions value="{!ContactNames}" /> </apex:selectList> </apex:pageBlock> </apex:form> </apex:page>
How could I force the "close date" to be mandatory when the "delivery stage" is equal to Closed, Customer Quit or Failed at the opportunity level?

Field Names:
Close Date: CloseDate
Customer Quit
Closed
Failed
Delivery Stage (picklist) FN: Delivery_Stage  API: Delivery_Stage__c

What I have so far:

AND(ispickval(Delivery_Stage__c,"Closed"), ispickval(Delivery_Stage__c,"Customer Quit"), ispickval(Delivery_Stage__c,"Failed"), (CloseDate =""))

Error: Incorrect parameter type for operator '='. Expected Date, received Text
Hello All,
Implementing a basic navigation component. No error while pushing the code to the scratch org, but when i click on the navigation buttons no action. Below is the image of our component on Account Record page.

User-added image

NavigationinLWC1.html
<template>
    <lightning-card title="Navigation Service in Lightning Web Component">
        <lightning-card title="Navigation to Record Page">
            <lightning-button-group>
                <lightning-button label="New Record Page" onclick={navigateToNewRecordPage}></lightning-button>
                <lightning-button label="Edit Record Page" onclick={navigateToEditRecordPage}></lightning-button>
                <lightning-button label="View Record Page" onclick={navigateToViewRecordPage}></lightning-button>
            </lightning-button-group>
        </lightning-card>
    </lightning-card>    
</template>

NavigationinLWC1.js
import { LightningElement,api } from 'lwc';
import {NavigationMixin} from 'lightning/navigation'
export default class NavigationinLWC1 extends LightningElement {
    @api recordId;
    navigateToNewRecordPage(){
        this[NavigationMixin.Navigate]({
            type:'standard__recordPage',
            attribute:{
                "recordId":this.recordId,
                "objectApiName":"Account",
                "actionName": "new"
            }
        });
    }

    navigateToEditRecordPage(){
        this[NavigationMixin.Navigate]({
            type:'standard__recordPage',
            attribute:{
                "recordId":this.recordId,
                "objectApiName":"Account",
                "actionName": "edit"
            }
        });
    }

    navigateToViewRecordPage(){
        this[NavigationMixin.Navigate]({
            type:'standard__recordPage',
            attribute:{
                "recordId":this.recordId,
                "objectApiName":"Account",
                "actionName": "view"
            }
        });
    }
}

Kindly help me out.
I have written the following test class and receive error "FATAL_ERROR System.DmlException: Insert failed. First exception on row 0 with id 0015B000015c9L1QAI; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]" when I run it, can anyone tell me what I am doing wrong?

@isTest
private class test_SaveAccountDetails {
    
    static testmethod void SaveAccountDetailTest() {
        Id RecordTypeIdPropAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        
        Account acctForm = new Account();
        acctForm.RecordTypeId=RecordTypeIdPropAccount;
        acctForm.Name = 'Test Account';
        acctForm.PropertyNumber__c = '123456';
        acctForm.PropertyType__c = 'Retail';
        acctForm.Phone = '8885551212';
        acctForm.PropertyStatus__c = 'Potential Acquisition';
        acctForm.Website = 'www.testsite.com';
        acctForm.Description = 'test account description';
        acctForm.Region__c = 'test region';
        acctForm.PurchaseDate__c = date.parse('2/2/2000');
        acctForm.PurchasePrice__c = 350000;    
        acctForm.DateSold__c = date.parse('2/2/2019');
        acctForm.SalePrice__c = 500000;
        acctForm.BillingCountry = 'United States';   
        acctForm.ShippingCountry = 'United States';
        acctForm.BillingStreet = '1313 Mockingbird Lane';
        acctForm.ShippingStreet = '100 Art Rooney Ave';
        acctForm.BillingCity = 'Springfield';
        acctForm.BillingState = 'Missouri';    
        acctForm.ShippingCity = 'Pittsburgh';
        acctForm.ShippingState = 'Pennsylvania';
        acctForm.BillingPostalCode = '12345';   
        acctForm.ShippingPostalCode = '15212';
        
        insert acctForm;
        
        Test.startTest();        
        SaveAccountDetails.SaveAccountDetail(acctForm);
        Test.stopTest();
            
        
        
    }
}

Here is the class I am trying to provide code coverage for:

public class SaveAccountDetails {
    
    @AuraEnabled
    public static id SaveAccountDetail(Account acctForm){
        //DML operation to save AcctForm Details
        system.debug(acctForm);
        Id recTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Property').getRecordTypeId();
        acctForm.RecordTypeId=recTypeId;
        insert acctForm;
        return acctForm.id;
    }
}

I would really appreciate any help provided!
({
	navigate : function(component, event, helper) {
        var navigateEvent = $A.get("e.force:navigateToComponent");
        navigateEvent.setParams({
            componentDef: "c.RegistrationFormTutorial"
        });
        navigateEvent.fire();
	}
})

I want to navigate from one lightning component to another component (RegistrationFormTutorial). I have written the above code. But I am getting error like this:


" This page has an error. You might just need to refresh it. Action failed: c:HtmlTryout$controller$navigate [Cannot read property 'setParams' of undefined] Failing descriptor: {c:HtmlTryout$controller$navigate} "

Could anyone please help me on this. Thanks in advance.
I have two classes and i am quite puzzle to write their test class and not getting any coverage for them

first Apex Class

global class WS_ZipUtil {

  /**
   * Receive Attachments info from Attachment ParentId
   */
  webService static String getAttachmentById( String sfdcId ){

    if( String.isEmpty( sfdcId ) ) return WS_Util.errorJson('Parameter sfdcId is required.');
    
    List<Attachment> attachmentList =  [SELECT Id, Name, Body, ContentType FROM Attachment WHERE Id = :sfdcId];
    if( attachmentList == null || attachmentList.size() == 0 ) return WS_Util.errorJson('Attachment not found.');
    return wrapAttachmentList( attachmentList );
  }

  //Format JSON String from AttachmentList
  private static String wrapAttachmentList( List<Attachment> attachmentList ){

    List<Object> dataList = new List<Object>();
    for( Attachment at : attachmentList ){
      Map<String, String> atMap = new Map<String, String>();
      //atMap.put( 'Id', at.Id );
      atMap.put( 'Name', at.Name );
      atMap.put( 'Body', EncodingUtil.base64Encode( at.Body ) );
      //atMap.put( 'ContentType', at.ContentType );
      dataList.add( atMap );
    }
    return WS_Util.normalJson( dataList );
  }


}


Second Apex Class

public class WS_Util {

  //Normal Status Code
  private static String API_STATUS_NORMAL = '200';
  //Error Status Code
  private static String API_STATUS_ERROR  = '400';

  /**
   * Normal JSON Response
   */
  public static String normalJson( Object respData ) {
    Map<String, Object> response = new Map<String, Object>();
    response.put('status', API_STATUS_NORMAL);
    if( respData != null ) response.put('data', respData);
    return JSON.serialize( response );
  }

  /**
   * Error JSON Response
   */
  public static String errorJson( String message ) {
    Map<String, Object> response = new Map<String, Object>();
    response.put('status', API_STATUS_ERROR);
    if( message != null ) response.put('error', message);
    return JSON.serialize( response );
  }

}
Hi,
I have created a modal to create new lead using lightning Edit form and have included the required fields. When i am taking <lightning:inputField fieldName="Name" /> to enter the name the data gets saved but since i have a custom requirement i am using different API to enter the First Name but after clicking SAVE, the data is not getting saved and throwing an error:
"An error occured when trying to update the the record. please try again."
Please help me resolve the issue to save the whole record with Firstname as well.
 
<aura:component implements="lightning:actionOverride,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" access="global" >
    <aura:attribute name="isOpen" type="boolean" default="true"/>
    <aura:attribute name="activeSections" type="List" default="['Pre-Enquiry Information','Scoring and Rating','Additional Information','System Information']" />
    
    <!--Use "slds-m-around_xx-large" class to add standard X-Large padding to the component--> 
    <div class="slds-m-around_xx-large">
        
        <!--Use aura:if tag to display Model Box, on the bese of conditions. [isOpen boolean attribute] -->   
        <aura:if isTrue="{!v.isOpen}">
            
            <!-- MODAL BOX Start --> 
            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
                <div class="slds-modal__container">
                    <!-- MODAL BOX HEADER Start -->
                    <header class="slds-modal__header">
                        <lightning:buttonIcon iconName="utility:close"
                                              onclick="{! c.closeModel }"
                                              alternativeText="close"
                                              variant="bare-inverse"
                                              class="slds-modal__close"/>
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">New Pre-Enquiry</h2>
                    </header>
                    <!-- MODAL BOX BODY Part Start -->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <lightning:recordEditForm aura:id ="newPreEnquiry" recordId="{!v.recordId}" objectApiName="Lead" onsuccess="{!c.handleSuccess}">
                            <lightning:accordion allowMultipleSectionsOpen="true" activeSectionName="{!v.activeSections}">
                                <lightning:accordionSection name="Pre-Enquiry Information" label="Pre-Enquiry Information">
                                    <lightning:messages />
                                    <!-- Forming a grid of two equal columns -->
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="Salutation" />
                                            <lightning:inputField fieldName="FirstName" required="true"/>
                                            <lightning:inputField fieldName="LastName" />
                                            <lightning:inputField fieldName="Name" class="slds-hide"/>
                                            <!--<lightning:inputField fieldName="Name" />-->
                                        </div>
                                        <div class="slds-size_1-of-2">
                                                
                                            <div style="padding-top: 25px"><lightning:inputField fieldName="LX_Other_Title__c" /></div>
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Location__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="MobilePhone" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="Email" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Other_Pre_Enquiry_Source__c" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Generated_By__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Category__c" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_PreEnquiry_Source__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="Company" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Customer_Type__c" />
                                        </div>
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Other_Preferred_Mode_of_Contact__c" />
                                        </div>
                                    </p>
                                    <p class="slds-grid">
                                        <div class="slds-size_1-of-2">
                                            <lightning:inputField fieldName="LX_Enquiry_Type__c" />
                                        </div>
                                    </p>
                                </lightning:accordionSection>
                            </lightning:accordion>
                        </lightning:recordEditForm>
                    </div>
                    <!--###### MODAL BOX FOOTER Part Start ######-->
                    <footer class="slds-modal__footer">
                        <lightning:button variant="neutral" 
                                          label="Cancel"
                                          title="Cancel"
                                          onclick="{!c.closeModel}"/>
                        <lightning:button variant="brand" 
                                          type="submit"
                                          name="save"
                                          label="Save"
                                          onclick="{!c.onRecordSubmit}"/>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
            <!--###### MODAL BOX Part END Here ######-->
            
        </aura:if>
    </div>   
</aura:component>

JS controller:
({
    myAction : function(component, event, helper) {
        
    },
    openModel: function(component, event, helper) {
        // for Display Model,set the "isOpen" attribute to "true"
        component.set("v.isOpen", true);
    },
    
    closeModel: function(component, event, helper) {
        // for Hide/Close Model,set the "isOpen" attribute to "False"  
        component.set("v.isOpen", false);
    },
    
    onRecordSubmit: function(component, event, helper) {
        event.preventDefault(); // stop form submission
        var eventFields = event.getParam("fields");
        component.find('newPreEnquiry').submit(eventFields);
    },
    
    /*handleSubmit : function(cmp, event, helper) {
        event.preventDefault();       // stop the form from submitting
        const fields = event.getParam('fields');
        fields.LastName = 'My Custom Last Name'; // modify a field
        cmp.find('myRecordForm').submit(fields);
    },*/
    
    handleSuccess : function(component, event, helper) {
        var preEnquiryRecord = event.getParams().response;
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
            "recordId": preEnquiryRecord.id,
            "slideDevName": "related"
        });
        navEvt.fire();
        
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            title : 'Success!',
            message: 'Pre-Enquiry record created.',
            duration:' 1000',
            key: 'info_alt',
            type: 'success',
            mode: 'dismissible'
        });
        toastEvent.fire();
    }
})
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 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 am trying to write an Apex class that could be run on a schedule. The aim is to iterate through objects and identify NULLs on a particular field and populate that field. So far I've written the below code but it is throwing the "Error: Compile Error: Variable does not exist: Auto_ID__c at line 16 column 56"
 
public class fixPersistentID {


List<String> objs = new List<String>{'ICP__c','Invoice_Number__c'};

        void populate_NULL_PID(){
        
                for(String s : objs){
                
                   String query = 'Select Auto_ID__c FROM '+ s +' WHERE Persistent_ID__c = null';
                   
                   List <sObject> sObj = database.query(query);
                   
                       for(sObject x : sObj){

                                x.Persistent_ID__c = x.Auto_ID__c;

                     }
                     
                   update x;
                
                
                }
                
               
        }


}



 
Hi! I am new with SF Apex programming, then I am stuck with a simple problem I think so.
After I added a Validation Rule to unable the user saves a new account without entering data in the fields (ShippingCity, ShippingPostalCode, ShippingStreet) I am facing some problems with a trigger test class.

I must be able to put fake values in my trigger test for these new fields that now are required field.

Could you help me, pls?
 
@isTest
    static void UpdateAccountProspect1() {        
        Boolean result = true;
        try{
            User testUser = SetupClassTest.createUserSalesRep('2801','testadmin@testorg.com', 'testadmin@testorg.com.prod');
            System.runAs(testUser){
                RecordTypeInfo rt = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Prospect_2801');
                List<Account> accToUpdate = SetupClassTest.generateNAccountsWithRT(1, rt.getRecordTypeId(), '2801');
                accToUpdate[0].RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Customer_2801').getRecordTypeId();
                update accToUpdate[0];
            }
        }catch(Exception e){
            System.debug('Línea: ' + e.getStackTraceString());
            result = false;
        }
        System.assert(result);
    }



 
trigger
trigger skipStage on Opportunity (before update,after update) {
     if(opp.Customer_confirms__c== true && opp.StageName==       'Negotiation/Review'){
       opp.StageName = 'Closed won';
    }
     else{opp.StageName = 'Proposal/Price Quote';
        }

or validation rule 

IF(AND(Customer_confirms__c==true,
ISPICKVAL(PRIORVALUE(StageName),"Negotiation/Review")),
   ISPICKVAL(PRIORVALUE(StageName),"Closed won"),
   ISPICKVAL(PRIORVALUE(StageName),"Proposal/Price Quote"))
    
}
Hi all,
I have working Code the sends an SMS  via Apex and Twilio, Great stuff. The trouble I am having is writing the Tests and I just need a little help. I don't do near enough Apex for my liking and I am feeling it here. 

IAny help/pointers would be most appreciated. 

Apex class:
public with sharing class Twilio {
    
    Public string text1 {get;set;}
    public boolean showmessage{get;set;}
    public string selectedvalue {get;set;} 
    
    private final contact acct;
    public Twilio(){}
    public Twilio(ApexPages.StandardController stdController) {
        this.acct = (contact)stdController.getRecord();       
    }
    
    Public static Void sendfromtwilio (string Fromnumber,string text,string tonumber) {
        
        errorResponseWrapper erw;
        configuration_setting__c cstt=new configuration_setting__c();
        cstt = [select Name,AccountSid__c, Active__c,AuthToken__c,Bulk_SMS__c,Contact_Phone_Number__c,Lead_Phone_Number__c,TestPhone__c FROM configuration_setting__c where Name='Twilio' limit 1];
        String account = cstt.AccountSid__c;
        String token = cstt.AuthToken__c;
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.twilio.com/2010-04-01/Accounts/'+account+'/SMS/Messages.json');
        
        req.setMethod('POST');
        
        String VERSION  = '3.2.0';
        
        req.setHeader('X-Twilio-Client', 'salesforce-' + VERSION);
        
        req.setHeader('User-Agent', 'twilio-salesforce/' + VERSION);
        
        req.setHeader('Accept', 'application/json');
        
        req.setHeader('Accept-Charset', 'utf-8');
        
        req.setHeader('Authorization','Basic '+EncodingUtil.base64Encode(Blob.valueOf(account+':' +token)));
        
        req.setBody('To='+EncodingUtil.urlEncode(+tonumber,'UTF-8')+'&From='+EncodingUtil.urlEncode(+Fromnumber,'UTF-8')+'&Body='+text);
        
        Http http = new Http();        
        HTTPResponse res = http.send(req);  
        System.debug(res.getBody());
        system.debug(res.getStatusCode());
        if(res.getStatusCode()==201)
        {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm,'SMS Sent Successfully'));
        } else{
            erw =(errorResponseWrapper)json.deserialize(res.getBody(),errorResponseWrapper.class);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,erw.message));
            System.debug('ERROR');
        }
    }
    public PageReference ok(){
        PageReference acctPage = new PageReference('/' +acct.Id);
        acctPage.setRedirect(true);
        return acctPage;
    }  
    public class errorResponseWrapper{
        String code;       
        String message;        
        String moreInfo;        
        String status;    
    }
}
  • January 14, 2020
  • Like
  • 0
Is this correct?
Salesforce provides the following types of relationships that can be established among objects:
Master-detail relationship.
Lookup relationship.
Self-relationship.
External lookup relationship.
Indirect lookup relationship. 
Hi All, 

I am facing issue of our test class we only got 13 perent code coverage please help
me

trigger autoCreateContactController on Case (before insert) {
    
    for(Trigger_Control__c tc:Trigger_Control__c.getAll().values())
    {
        if( tc.Enable_Auto_Create_contact_Trigger__c==true)
        {
            
              for(case cs:trigger.new)
       {
          
           if(userinfo.getName()=='Automated Workflow'){   
               contact[] lstcontact= [select id from contact where email=:cs.SuppliedEmail limit 1];
               
                    if(!lstcontact.isEmpty()) 
                   {
                  String contId=lstcontact[0].id;
                    if(contId!=null)
                    {
                    cs.ContactId=contId;
                    }
                } 
                else { 
                   
                    String leftPart = cs.Suppliedname;
                    String[] leftPartSplitted = leftPart.split('\\s+');
                    if(leftPart!=null || leftPart!='') 
                    {
                        if(leftPartSplitted.size() == 3)
                        {
                            String firstName = leftPartSplitted[0]; 
                            String lastName = leftPartSplitted[1]; 
                            String middlename=leftPartSplitted[2]; 
                            contact con1 =new contact(); 
                            con1.firstname=firstName;
                            con1.LastName=lastName+middlename;
                            con1.Email=cs.SuppliedEmail;
                            con1.AccountId='0010W00002MuDcQQAV';
                            insert con1; 
                            cs.ContactId=con1.Id; 
                        }  
                        else if(leftPartSplitted.size() == 2) 
                        { 
                            String firstName = leftPartSplitted[0];
                            String lastName = leftPartSplitted[1]; 
                            contact con1 =new contact();
                            con1.firstname=firstName; 
                            con1.LastName=lastName;  
                            con1.Email=cs.SuppliedEmail;  
                            con1.AccountId='0010W00002MuDcQQAV';  
                            insert con1;   
                            cs.ContactId=con1.Id; 
                        }
                        else if(leftPartSplitted.size() == 1)
                        { 
                            String lastName = leftPartSplitted[0]; 
                            contact con1 =new contact();
                            con1.LastName=lastName;
                            con1.Email=cs.SuppliedEmail;
                            con1.AccountId='0010W00002MuDcQQAV';
                            insert con1; 
                            cs.ContactId=con1.Id;    
                }
            }
                               
                    
               } 
               }}}
            
    }}


My test class is 

@isTest
public class AutoCreateContactControllerTest {

@isTest
    public Static void SpamTestmethod()
    {  Account acc = new Account(Name='MassBay');
        insert acc;
        
        Contact con = new Contact(AccountId=acc.Id,LastName='test',Email='tttt@test.com');
        insert con;
        Trigger_Control__c tc=new Trigger_Control__c();
        tc.Enable_Auto_Create_contact_Trigger__c=true;
        tc.Name='test tc';
        insert tc;
     
     List<case>lstcase=new List<case>();
          
       
            List<RecordType> listRecType = [select Id from RecordType where sObjectType = 'Case' And Name = 'MassBayCC_Ticket'];
            Case cs = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
      
        cs.Subject='tesr';
        cs.Description='Test description';
         cs.SuppliedEmail='tttt@test.com';
        cs.SuppliedName='hello world';
          lstcase.add(cs);
          Case cs1 = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
        
        cs1.Subject='tesr';
        cs1.Description='Test Description';
        cs1.SuppliedEmail='tttt@test.com';
        
        
        
        cs1.SuppliedName='hello world world';
          lstcase.add(cs1);
          Case cs2 = new Case(RecordTypeId = listRecType[0].Id,AccountId=acc.Id,ContactId=con.Id);
        cs2.Subject='tesr';
        cs2.Description='Test Description';
        cs2.SuppliedEmail='tttt@test.com';
        cs2.SuppliedName='hello';
        lstcase.add(cs2);
          insert lstcase;
        
       
    }
}
Hi There,
I am using flow for creating related record .I am struggling to redirect the flow to record detail page after save.Please advise an appropriate approach.

Note: I am launching the flow from url and passing Id.

Thanks in advance.
I am trying to write an inner join and noticed from some other threads you need to write it similar to this 

services/data/v47.0/query/?q=SELECT+Id,Name,(select+OpportunityId,Price+From+OpportunityLineItem) +From+Opportunity+Where+Opportunity.Id+=+OpportunityLineItem.OpportunityId

this returns a MALFORMED_QUERY errorCode. Is this query possible if so what would be the correct way to write this. 

Thanks in advance
Hey guys, 

Looking to write a test class for the following: 

trigger OpportunityAmountTrigger on Opportunity (Before Insert, Before Update) {
    for(Opportunity o : Trigger.New){
    if(trigger.isinsert && o.amount < 5000)
    o.addError('Amount can not be less than 5000');
    else if (Trigger.isUpdate && o.amount < 3000)
    o.adderror('Amount can not be updated to less than 3000');
 
    }
}

Here is what I have so far, but not sure where to go from here:

@isTest
public class OpportunityAmountTriggerTest {
    
    @isTest static void testOpportunity()
    {
        Integer Opportunity= Opportunity.amount(4000);
        System.assertEquals('Amount can not be less than 5000', Opportunity);
    }
}
Hello, I am an admin adventuring into learning code and I cannot figure out why the following Lightning Web Component is not working. (I've left out some of the code for simplicity.) Thank you!

HTML:
<p>Total Licenses:<span class="slds-p-horizontal_small">{totalPartnerLicenses}</span></p>

JS:
import { LightningElement, track, wire } from 'lwc';
import queryTotalPartnerLicenses from '@salesforce/apex/queryForLicenses.queryTotalPartnerLicenses';
export default class PartnerCommunityLicenses extends LightningElement {
@track totalPartnerLicenses = 7;
@wire(queryTotalPartnerLicenses) totalPartnerLicenses;
}

APEX CLASS:
public with sharing class queryForLicenses {
@AuraEnabled(cacheable=true)
public static Integer queryTotalPartnerLicenses(){
List<UserLicense> totalPL = [SELECT ID, TotalLicenses FROM UserLicense WHERE Name = 'Partner Community'];
UserLicense pl = new UserLicense();
Integer numTotalLicenses;

if(totalPl.size()>0){
pl = totalPL[0];
numTotalLicenses = Integer.valueOf(pl.TotalLicenses);
}
else {
numTotalLicenses=0;
}
return numTotalLicenses;
}
}
Hi all I have a test class for this invokable method but only getting 31% coverage.. Any help would be appreciated to increase coverage.. been banging my head on it all weekend.. Thanks in advance... 

---Test---
@isTest
public class DefaultEntitlementTest {
    static testmethod void ValidateDefaultEntitlementAction() {
        Account[] acc = new Account[] {
            new Account(Name='Test Account 1'), 
            new Account(Name='Test Account 2')
        };
        insert acc;
        
        Contact[] contacts = new Contact[] {
            new Contact(FirstName='Test 1', LastName='McTesty', AccountId = acc[0].id),
            new Contact(FirstName='Test 2', LastName='McTesty', AccountId = acc[0].id)
        };
        insert contacts;
        
        Id entitlementProcessId = [SELECT Id FROM SlaProcess WHERE SObjectType = 'Case' LIMIT 1].Id;
        
        Entitlement[] ent = new Entitlement[] {
            new Entitlement (AccountId=acc[0].Id, SLAProcessId = entitlementProcessId, Name = 'Test Entitlement Account',
                                           StartDate = system.today().addDays(-1), EndDate = system.today().addDays(5)),
            new Entitlement (AccountId=acc[1].id, SLAProcessId = entitlementProcessId, Name = 'Test Entitlement Contact',
                                           StartDate = system.today().addDays(-1), EndDate = system.today().addDays(5))
        };
        insert ent;
        
        EntitlementContact ec = new EntitlementContact(ContactId = contacts[0].id, EntitlementId = ent[1].id);
        insert ec;
        
        
        Case c = new Case(AccountId = acc[0].id, ContactId = contacts[0].id, Subject='Test');
        insert c;
        
        c = [SELECT Id, EntitlementId FROM Case WHERE Id =: c.id LIMIT 1];
        system.assertEquals(ent[1].id, c.EntitlementId);
        
        c = new Case(AccountId = acc[0].id, ContactId = contacts[1].id, Subject='Test');
        insert c;
        
        c = [SELECT Id, EntitlementId FROM Case WHERE Id =: c.id LIMIT 1];
        system.assertEquals(ent[0].id, c.EntitlementId);
    }
}


---Method---

public class DefaultEntitlementAction {
    @InvocableMethod(label='Update Default Entitlements' description='Determines the default Entitlement for the Case and returns the updated Cases.')
    public static void updateDefaultEntitlements(List<Case> casesToUpdate) {
        List<Case> cases = [
            SELECT AccountId, EntitlementId, AssetId 
            FROM Case 
            WHERE Id IN:new Map<Id, Case>(casesToUpdate).keySet()
        ];
        
        Set<Id> accountIds = new Set<Id>();
            
        for (Case c : cases){
            if (c.EntitlementId == null && c.AccountId != null) {
                accountIds.add(c.AccountId);
            }
        }

        if(accountIds.size() > 0) {    
            List <Entitlement> entitlements = [
                SELECT StartDate, EndDate, AccountId, AssetId
                FROM Entitlement
                WHERE AccountId in :accountIds 
                    AND StartDate <= TODAY 
                    AND EndDate >= TODAY
            ];
            
            if(entitlements.size() > 0) {       
                Map<Id, Entitlement> entitlementsByAccountId = new Map<Id, Entitlement>();
                
                for(Entitlement e : entitlements) {
                    entitlementsByAccountId.put(e.AccountId, e);
                }
                
                for(Case c : cases){
                    if(c.EntitlementId == null && c.AccountId != null) {
                        Entitlement e = entitlementsByAccountId.get(c.AccountId);
                        
                        if(e != null) {
                            c.EntitlementId = e.Id;
                            
                            if(c.AssetId == null && e.AssetId != null) {
                                c.AssetId = e.AssetId;
                            }
                        }
                    }
                }
                
                update cases;
            }
        }
    }
}
Hi all,
I have a requirement of showing small icon beside records in datatable 
I am adding a picture for reference
User-added imagehow to do this?

thanks in advance
Hi,
I cannot create a new Activity History record when using message.setSaveAsActivity(true);
 
This is my code:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String AccId = apexpages.currentpage().getparameters().get('AccId');
            mail.setUseSignature(false);
            mail.setToAddresses(emaillist);
            mail.setSubject(' Details'); 
   	    mail.setSaveAsActivity(true);
            mail.setTargetObjectId(AccId);
            mail.setBccSender(true); 
            mail.setHtmlBody(templateBody);
            System.debug('===t===='+successmsg);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Email send successfully'));

Thanks,
Chiyan SFDC
Lightning datatable does not reflect Account.Name, Owner.Name, Created By. Name. what is the error?
doInit : function(component, event, helper) {
        component.set('v.mycolumns', [                 
            {label: 'Account Name', fieldName: 'Name', type: 'text',sortable: true},
            {label: 'Email', fieldName: 'Email', type: 'Email', sortable: true},
            {label: 'Contact Level', fieldName: 'Contact_Level__c', type: 'picklist',sortable: true},
            {label: 'Account', fieldName: 'Account.Name', type: 'text',sortable: true},
            {label: 'Owner', fieldName: 'Owner.Name', type: 'text',sortable: true},
            {label: 'Created By', fieldName: 'CreatedBy.Name', type: 'text', sortable: true},
            {label: 'Created Date', fieldName: 'CreatedDate', type: 'data',sortable: true},
            {label:'Action',type:  'button',typeAttributes:
             {iconName: 'utility:view',label: 'Del',name: 'Del', disabled: false,value: 'viewBtn'}
            }
        ]);
I am extremely new to LWC. InFACT just new to apex as well..but my first assignment i have to create a small component which takes a text value and is appended to opportunity record existing field and then sends an email to owners managers...i have the basic HTML, JAVASCRIPT AND APEX written,

However i was told not use wire and instead call the apex imperatively, So On click of submit button the apex methos will udpate the opportunity record and send an email and I have to reload the existing opporecord page with updated values.
Can someone help me correct my javascript handleclick funcation?
javascript
import { LightningElement, track, api } from 'lwc';
import updateCommentsNextStepsOnOpportunity from "@salesforce/apex/opportunityCommentController.updateCommentsNextStepsOnOpportunity";


export default class OpportunityCommentUpdate extends LightningElement {
  
    @api recordId;
    @track newComment = '';

    
	 trackComment(event){
          this.newComment = event.detail.value;
      }


	  handleClick() {
     
      updateCommentsNextStepsOnOpportunity(recordId, newComment)
        .then(result => {
          
          window.location = "opportunity/" + this.recordId;
        })
        .catch(error => {
          this.error = error;
        });
    }
  
     

	  handleCancel(event){
	 
    }
	}


APEX:
public without sharing class opportunityCommentController {
    

	
	 @AuraEnabled
	 public static void updateCommentsNextStepsOnOpportunity(Id recordId, String newComment) {
        
        
        
        Opportunity selectedOpp = [SELECT Id, Comments_Next_Steps__c, Description, OwnerId from opportunity where id =: recordId ];
        
        selectedOpp.Comments_Next_Steps__c=System.today().format()+' '+ newComment;
        string temp = selectedOpp.Description;
        
        if(temp==null && !string.isNotBlank(temp)){
            selectedOpp.Description = selectedOpp.Comments_Next_Steps__c;  
            
        }else if(temp!=null && string.isNotBlank(temp)){
            selectedOpp.Description =  selectedOpp.Comments_Next_Steps__c +'\n' +temp;
        }
        
        
        update selectedOpp;
		sendEmailToRVPandRD(selectedOpp);
    }
    
	
	
    public static void sendEmailToRVPandRD(Opportunity selectedOpp) {
        
        List<String> emailList = new List<String>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        
        User getRVPRDEmail = [SELECT Id, Reports_to_RVP__r.Email, Reports_to_RD__r.Email, Username FROM User where id =:selectedOpp.OwnerId];
        
        emailList.add(getRVPRDEmail.Reports_to_RVP__r.Email);
        emailList.add(getRVPRDEmail.Reports_to_RD__r.Email);
        Messaging.SingleEmailMessage sendEmailmsg = new Messaging.SingleEmailMessage();
        sendEmailmsg.toaddresses= emailList;
        string body='';
        body += '<html></br> </br>' + 'A comment has been added to the opportunity record , '
            + '<a href="'+URL.getSalesforceBaseUrl().toExternalForm()
            +'/'+ selectedOpp.id +'">' + '</a>';
        body +=  '</body></html>';
        
        sendEmailmsg.setHtmlBody(body);
        string Subject = 'A comment has been added to the opportunity record '+''+ selectedOpp.Name;
        sendEmailmsg.setSubject(Subject);
        
        mails.add(sendEmailmsg);
        
  
    Messaging.sendEmail(mails);
    
}
}


html
template>
    <lightning-card title="Add Comments">
        <div class="slds-m-around_medium">
          

                <lightning-textarea name="input1" label="Enter new comment" onchange={trackComment}></lightning-textarea>
                <lightning-button variant="neutral"
                                  label="Cancel"
                                  title="Cancel"
                                  type="text"
                                  onclick={handleCancel}
                                  class="slds-m-right_small"></lightning-button>

                <lightning-button variant="brand"
                                  label="Submit"
                                  title="Submit"
                                  onclick={handleClick}
                                  type="submit"></lightning-button>
           
        </div>
    </lightning-card>
</template>

 
Hello Everyone,

I had an issue with Commandbutton which I need to redirect the page from the Visualforce page to some other company Website Contact Us page.

Here is my CommandButton code and Controller class code.

VF Page CommandButton:

 <apex:commandButton style="color:white; background-color:red; background-image:none; width:150px; height:35px" action="{!Cancel}" value="Cancel"  />

Controller Class:

 public PageReference Cancel(){
        PageReference pr = new PageReference('/www.bren.com/residential/contact');
        pr.setRedirect(true);
        return pr;
    }


Please help me with this issue.

Thanks and Regards,
Azar Khasim.
Hello, I'm fairly new to salesforce and still learning. I've built a formula field that unchecks a box if an entitlement has expired by date. Then I built a workflow to kickoff when the checkbox is unchecked and have it  update a field. The formula field works as expected, but the workflow doesn't kickoff. Can i not do this with formula fields?  

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