• Raj Vakati
  • ALL STAR
  • 25655 Points
  • Member since 2016

  • Chatter
    Feed
  • 842
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 7358
    Replies
Hi,

I need to create a custom field on opportunity that shows the amount of all opportunities with the same CloseDate month and year.

I've tried a trigger, but i'm geting this error "SELF_REFERENCE_FROM_TRIGGER". I can't update the field of the record that fires the trigger.

How can I reach this? 

Trigger:
 
trigger calculateTotalAmount on Opportunity(after update, after insert) {

    double totalAmount;
    date firstDayReference;
    date lastDayReference;
    Integer daysInMonth;

    If(Trigger.IsInsert || Trigger.IsUpdate) {
        For(Opportunity opp: Trigger.New) {

            daysInMonth = Date.daysInMonth(opp.CloseDate.year(), opp.CloseDate.month());
            firstDayReference = date.newinstance(opp.CloseDate.year(), opp.CloseDate.month(), 1);
            lastDayReference = date.newinstance(opp.CloseDate.year(), opp.CloseDate.month(), daysInMonth);

            List < Opportunity > Oppor = [SELECT ID, Name, CloseDate, Amount
                                            FROM Opportunity
                                           WHERE CloseDate >=: firstDayReference AND CloseDate <=: lastDayReference AND StageName = 'Closed Won'
                                         ];


            For(Opportunity o: Oppor) {

                totalAmount = totalAmount + o.Amount;
            }


            For(Opportunity o: Oppor) {
                o.total_amount__c = totalAmount;

            }
            
            update Oppor;

        }
    }
}


 
Create an Apex class called 'AddPrimaryContact' that implements the Queueable interface.

Create a constructor for the class that accepts as its first argument a Contact sObject and a second argument as a string for the State abbreviation.

The execute method must query for a maximum of 200 Accounts with the BillingState specified by the State abbreviation passed into the constructor and insert the Contact sObject record associated to each Account. Look at the sObject clone() method.

Create an Apex test class called 'AddPrimaryContactTest'.

In the test class, insert 50 Account records for BillingState "NY" and 50 Account records for BillingState "CA". Create an instance of the AddPrimaryContact class, enqueue the job and assert that a Contact record was inserted for each of the 50 Accounts with the BillingState of "CA".
When I eneter User name and Date in the input fields then click on login button , it should check whether that User name which Iam referring to last name in lead and that date of birth  is present in the Lead. If its present then it should Login and redirect to a visualforce page. Its working fine if iam doing without date when when Iam querying date its throwing the Null pointer exceptio, Attempt to reference null object error. I think its error in the query.Date should be converted in hh:mm:ss i guess please help.

Please  find the code.

public with sharing class LoginCntrl {
    public string userName{get;set;}
   public Lead Dateofbirth{get;set;}
   
  
    public pageReference doLogin() {
         
        if(String.isBlank(userName)) return null;  
        
        string dateformat;
        
        
        
              
        List<Lead> conls = [select id, lastname from Lead where LastName = :userName and date_of_birth__c=:Dateofbirth.Date_of_Birth__c];
        system.debug('dddddddddddddddddd'+conls );
        if(conls.size() == 1 ) {
            return new pageReference('/apex/studentpersonaldetails');
        }
        else {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please Enter correct User Name or Date of Birth'));

        userName = null;
        Dateofbirth = null;
            return null;
        
        }
        
    }

}

VF :-

<apex:page controller="LoginCntrl" showHeader="false" sidebar="false">
    <apex:form >
        <apex:image id="theImage" value="{!$Resource.nmims2}" width="350" height="60"/><br/>

    <apex:pageBlock title="Login Page" >
    <apex:pageMessages ></apex:pageMessages>

    <br/>

      User Name :  <apex:inputtext value="{!userName}"/> <br/>
       <br/>Date of birth: <apex:inputfield value="{!Dateofbirth.Date_of_Birth__c}"/><br/>
       <br/>
    
        <apex:commandButton style="margin-left:10px" value="Login" action="{!doLogin}"/>
</apex:pageBlock>
    </apex:form>
</apex:page>

 
Hello, 
Trying to cancel an apex batch job but no luck making it work. 

This is the apex code I'm using and the error results are below. Any help is greatly appreciated!
 
string SCHEDULE_NAME = 'MergeMetricsCalculationBatchable';
System.abortJob(SCHEDULE_NAME);
 
Execute anonumous error

Line: 2, Column: 1
System.StringException: Only CronTrigger IDs and batch, future, and queueable job IDs are supported.

 
  • March 17, 2019
  • Like
  • 0
Hi Team,

While trying to group the Temperature to kWh Research Report with SolarBot Model, I am not able to find SolarBot Model.

Please assist, thanks
Vinay Kumar Salve
Hello,

I am not a developer but would like to learn a few basic things.
One of which I am working on is to auto-create a lead from a case based on certain criteria.  The code below works but I need to get the lastname from Contact instead of an ID.  Can anyone show me how?  Thanks.

trigger AutoCreateLead on Case (before insert) 
{
    case c=trigger.new[0];
    if(c.Approved_for_Lead__c  == TRUE)
  {
    list<lead> 
    l = [select id, Email from Lead where Email = :c.ContactEmail];
     if(l.size()==0)
    {
      lead l1=new lead(lastname=c.ContactId , Email=c.ContactEmail, Company=c.SuppliedName, LeadSource='Converted From Case', Status = 'Open - Not Contacted', Title='Converted From Case', Phone=c.ContactPhone);
      insert l1;
    }
  }
}
Hello All,
I am trying to work with the ActivityHistory Object and wanted to confirm what I think the issue is.
I have a query where I want to return records where the record does not contain an activty:
Select Id,Name FROM test__c  WHERE  Status__c='Registered' AND ID NOT IN (SELECT WhatID FROM ActivityHistories where Activity_Subtype__c='stuff')

I am assuming that it is not possible to query against the ActivityHistory object correct?
Hello, 

I'm getting stuck when I want to write a test class for this class. Please can you help me out? Thanks in advance.

public class UpsertCollectantenV2 {

    public String strNote { get; set; }
    public String strInitials { get; set; }
    public String strSalutation { get; set; }
    public String strMobiel { get; set; }
    public String strPlace { get; set; }
    public String strSuffix { get; set; }
    public decimal strHousenumber { get; set; }
    public String strPostalStreet { get; set; }
    public String strPostalCode { get; set; }
    public Date strDateOfBirth { get; set; }
    public String strPhone { get; set; }
    public String strEmail { get; set; }
    public String strLastname { get; set; }
    public String strFirstname { get; set; }
    public String description { get; set; }
    
    public PageReference save() {

        String strSleutelAccountKlein = 'H-' +
            strLastname.left(3) +  '-' +
            strPostalCode.left(4) + strPostalCode.right(2) +  '-' +
            strHousenumber + strSuffix; 
        
        String strSleutelAccount = strSleutelAccountKlein.ToUpperCase();
    
        String strSleutelContactKlein = 'P-' +
            strSalutation.replaceAll('De heer', 'M').replaceAll('Mevrouw', 'V') + '-' +
            strFirstname.left(1) + '-' +
            strLastname.left(3) +  '-' +
            strPostalCode.left(4) + strPostalCode.right(2) +  '-' +
            strHousenumber + strSuffix; 
        
        String strSleutelContact = strSleutelContactKlein.ToUpperCase();  
        
        //Check of account bestaat  
        Account[] oldAccounts = [SELECT Account.Id 
                              FROM Account 
                              WHERE NAW_Sleutel__c = :strSleutelAccount
                              LIMIT 1];
        
        // loop through them and update the Description field
        for (account acct : oldAccounts) {
          acct.Description = description;
        }
                
        
            if(oldAccounts.size() >0) {
            
                // Check of contact bestaat
                Contact[] oldContacts = [SELECT Account.Id 
                                      FROM Contact 
                                      WHERE NAW_Sleutel__c = :strSleutelContact
                                      LIMIT 1];
                
                // loop through them and update the Description field
                for (contact cont : oldContacts) {
                  cont.Description = description;
                }                
                    
                if(oldContacts.size() >0) {
                    
                    // Bestaand contact ophalen
                    Contact queriedContact = [SELECT Account.Id 
                                          FROM Contact 
                                          WHERE NAW_Sleutel__c = :strSleutelContact
                                          LIMIT 1];
                                                                            
                    // Update the contact's phone number
                    queriedContact.Salutation = strSalutation;    
                    queriedContact.bf_Voorletters__c = strInitials;
                    queriedContact.FirstName = strFirstName;    
                    queriedContact.Phone = strPhone;   
                    queriedContact.Email = strEmail;
                    queriedContact.Birthdate= strDateOfBirth;
                    queriedContact.MobilePhone = strMobiel;
                    queriedContact.Notities_ORCA__c = strNote;
                           
                    // Update the related account fields
                    queriedContact.Account.soco__Billing_Zipcode__c = strPostalCode;
                    queriedContact.Account.soco__Billing_Street__c = strPostalStreet;
                    queriedContact.Account.soco__Billing_Housenumber__c = strHousenumber;     
                    queriedContact.Account.soco__Billing_Suffix__c = strSuffix;
                    queriedContact.Account.soco__Billing_City__c = strPlace;
                            
                    // Make two separate calls 
                    // 1. This call is to update the contact's phone.
                    update queriedContact;
                    // 2. This call is to update the related account fields.
                    update queriedContact.Account;
                }    
                else {
            
                    //Bestaand account ophalen
                    Account queriedAccount = [SELECT Account.Id 
                                              FROM Account 
                                              WHERE NAW_Sleutel__c = :strSleutelAccount
                                              LIMIT 1];
                                              
                        // Voeg contact toe aan account
                        Contact con = new Contact(
                            Salutation= strSalutation,
                            bf_Voorletters__c = strInitials,
                            FirstName= strFirstName,
                            LastName= strLastname,
                            Phone= strPhone,
                            MobilePhone = strMobiel,
                            Email = strEmail,
                            Birthdate= strDateOfBirth,
                            Notities_ORCA__c = strNote,
                            AccountId=queriedAccount.ID);
                        insert con;
                    
                        ID conID = con.ID;
                
                        // Contact opvoeren als campagnelid
                        CampaignMember mem = new CampaignMember(
                            CampaignId = '7010Y000000I783', //Website BWS collectevrijwilliger
                            ContactId = conID);
                        // Insert the campaign member by using DML
                        insert mem;
                
                }
            }             
            else
            {
                // Nieuw account opvoeren
                Account acct = new Account(
                    Name= strLastName, 
                    soco__Billing_Street__c = strPostalStreet, 
                    soco__Billing_Zipcode__c = strPostalCode, 
                    soco__Billing_Housenumber__c = strHousenumber,     
                    soco__Billing_Suffix__c = strSuffix,
                    soco__Billing_City__c = strPlace,   
                    RecordTypeId = '0120Y000000k85mQAA');     
                // Insert the account by using DML
                insert acct;
                
                ID acctID = acct.ID;
            
                // Nieuw contact toevoegen aan account
                Contact con = new Contact(
                    Salutation = strSalutation,
                    bf_Voorletters__c = strInitials,
                    FirstName = strFirstName,
                    LastName = strLastName,
                    Phone = strPhone,
                    MobilePhone = strMobiel,
                    Email = strEmail,
                    Birthdate = strDateOfBirth,
                    Notities_ORCA__c = strNote,
                    AccountId = acctID);
                // Insert the contact by using DML
                insert con;
            
                ID conID = con.ID;
            
                // Contact opvoeren als campagnelid
                CampaignMember mem = new CampaignMember(
                    CampaignId = '7010Y000000I783', //Website BWS collectevrijwilliger
                    ContactId = conID);
                // Insert the campaign member by using DML
                insert mem;
            
            }
            
        Pagereference pr = New PageReference('/testsite');
        return pr;
        //return null;            
        
    }
}
I have an icon associated with a custom object, it is the Handsaw icon.  How do I show this icon in my lightning component?

Do I have to hard code the icon as custom70?
https://www.lightningdesignsystem.com/icons/
 

global class DuplicateContactMergeBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext bc){
       // collect the batches of records or objects to be passed to execute. 
       // DuplicateRecordSet is a list of Contacts (Duplicate RecordItems) idenified as Duplicates by the Duplicate Rule
    	
		string conduplicateruleid;
		list<DuplicateRulesId__c> cs = [select id, ContactDuplicateRuleId__c from DuplicateRulesId__c limit 1];
		if(cs!=null && cs.size() > 0 ){
			for(DuplicateRulesId__c custsetting: cs){
				
			   conduplicateruleid = custsetting.ContactDuplicateRuleId__c;
				system.debug('++++++++++++++++++    ' +conduplicateruleid);
			 }
		}

		// Fetch Id and Name of the Duplicate Record Set 

		return Database.getQueryLocator([
                SELECT id, name 
                FROM DuplicateRecordSet
                Where DuplicateRuleId = :conduplicateruleid 
            ]);  
		
    }
	
	global void execute(Database.BatchableContext BC, List<DuplicateRecordSet> scope) {
              
       //call MergeContacts method to process each batch of records
        MergeContacts(scope); 
        
    }

	public static void  MergeContacts(List<DuplicateRecordSet> dupset){
	
		//iterate through each DuplicateRecordSet, and create a map of duplicaterecordset<Id, DuplicateRecordSet> 
		Map<Id, DuplicateRecordSet> mapDuplicateRecordSet =  new Map<Id,DuplicateRecordSet>();

		if(dupset!=null && dupset.size()>0){
			for(DuplicateRecordSet drs : dupset){
				mapDuplicateRecordSet.put(drs.Id, drs);
			}
		}
		system.debug('map of duplicate record set' +mapDuplicateRecordSet);
		Map<Id, Set<Id>> mapDuplicateRecordItem =  new Map<Id, Set<Id>>();
		for(DuplicateRecordItem drI : [SELECT Id,RecordId, DuplicateRecordSetId 
									   FROM DuplicateRecordItem 
									   where DuplicateRecordSetId IN :mapDuplicateRecordSet.keyset()]){
					
					System.debug('Duplicate record Items: ' +drI);
					if(drI!=null && !mapDuplicateRecordItem.containskey(drI.DuplicateRecordSetId)){
						mapDuplicateRecordItem.put(drI.DuplicateRecordSetId, new Set<Id>{drI.RecordId}); 
					}
					else{
						mapDuplicateRecordItem.get(drI.DuplicateRecordSetId).add(drI.RecordId); 
					}
		} 

		// create a list of contacts that need to be merged 
		list<id> lstContactId = new list<id>(); 
		Set<Id>  setContactId = new set<id>();
		list<contact> mastercontact = new list<contact>();

		// iterate through all DuplicateRecordSet records that has child records 
		for(DuplicateRecordSet dr : [SELECT Id 
									 FROM DuplicateRecordSet 
									 where Id IN : mapDuplicateRecordItem.keyset()]){
			
			// Collect all disctinct contacts from the duplicaterecorditems
			setContactId =  mapDuplicateRecordItem.get(dr.Id);
			system.debug('The elements in the setofid are :' +setContactId.size());
			system.debug('Each of these elements is :' +setContactId);                             
										 
		}

		for(Contact con : [SELECT Id, lastname,email, ownerid,phone 
							   FROM Contact 
							   WHERE Id In : setContactId 
							   order by CreatedDate DESC LIMIT 1]){		
													   
							   IF(con!=null){
								mastercontact.add(con);
							   }
							   setContactId.remove(con.Id);  
							   lstContactId.addAll(setContactId);  
		}

		system.debug('master contact ' +mastercontact[0]);
		system.debug('new elemensts in the setContactId' +setContactId);
		system.debug('list of dupicated contacts ' +lstContactId);

		if(mastercontact.size()>0 && mastercontact!=null){
			try{
				Database.merge (mastercontact[0],lstContactId, true);
			}	catch (DmlException e) {
				// Process exception
				System.debug('An unexpected error has occurred: ' + e.getMessage()); 
			} 
		}
	
	}

	global void finish(Database.BatchableContext bc){
       // execute any post-processing operations
    }   

}

@isTest 
public class DuplicateContactMergeBatchTest{

    public static testMethod void testContactMerge() {
        
       	// Create a test user        	
       	User oUser = TestDataHelper.createUser('Lender', 'Testra1', 'testra1@emailtest.com', 'Dealer Sales Representative', true);
       	
       	// Create test dealer Accounts
       	Account oAccount1 = TestDataHelper.createAccount('Testonera Account-1', 'Dealer Account', 'RAA-1', oUser.Id, false);
       	Account oAccount2 = TestDataHelper.createAccount('Testtwora Account-2', 'Dealer Account', 'RAA-2', oUser.Id, false);
        
        List<Account> accounts = new List<Account>{oAccount1,oAccount2};
        
        insert accounts;
                
        System.assertEquals( 1, [ SELECT count() FROM Account WHERE id = :oAccount1.id ] );
        System.assertEquals( 1, [ SELECT count() FROM Account WHERE id = :oAccount2.id ] );
        
        //Create a Dealer Contact record
        Contact oContact1 = TestDataHelper.createContact(oAccount1.Id, 'TestConOne', 'TestLastname', 'Dealer Contact', '9995551212', oUser.Id, true);
        
        Contact oContact2 = oContact1.clone(); 
        
        insert oContact2;
        
        System.assertEquals( 1, [ SELECT count() FROM Contact WHERE id = :oContact1.id ] );
        System.assertEquals( 1, [ SELECT count() FROM Contact WHERE id = :oContact2.id ] );
        
        list<Contact> contacts = new list<Contact>();
        contacts.add(oContact1);
        contacts.add(oContact2);
        
        system.debug('The contactlistsize is ' +contacts.size() );
        
        // if no duplicate record sets have been created yet
        // then let's manually insert them so we can test the merge
        Integer dupeCount = [ SELECT count() FROM DuplicateRecordItem WHERE recordId IN :contacts ];
        system.debug('Thiiiiiii ' +dupeCount);
        if ( dupeCount == 0 ) {
            insertDuplicateRecordSet( contacts );
        }
        
        Test.startTest();
            DuplicateContactMergeSched sh1 = new DuplicateContactMergeSched();
            String sch = '0 0 23 * * ?';
            system.schedule('Test DuplicateContactMergeSched', sch, sh1);
        Test.stopTest();
        
    }
    
     private static void insertDuplicateRecordSet( List<Contact> contacts ) {
     
        //Database.DMLOptions insertDML = new Database.DMLOptions(); 
        //insertDML.DuplicateRuleHeader.AllowSave = true; 
        
        DuplicateRule rule = [ SELECT id FROM DuplicateRule 
                                WHERE DeveloperName = 'Standard_Rule_for_Contacts_with_Duplicate_Contacts' LIMIT 1 ];
                                
                                system.debug('RULLLLLLLLLeeee ' +rule.id);
                                
        //Database.SaveResult[] sr = Database.insert(contacts, insertDML);        
        DuplicateRecordSet drs = new DuplicateRecordSet(
            duplicateRuleId = rule.id
        );
        
        insert drs;
        
        system.debug('>>>>>>>>>>>>' +drs);

        List<DuplicateRecordItem> items = new List<DuplicateRecordItem>();
        
        for ( Contact cnt : contacts ) {
            items.add( new DuplicateRecordItem(
                duplicateRecordSetId = drs.id,
                recordId = cnt.id
            ));
        }
        
        insert items;
        
    }
    
}


 
global class DuplicateContactMergeSched implements Schedulable{
   global void execute(SchedulableContext SC) {
    DuplicateContactMergeBatch b = new DuplicateContactMergeBatch(); 
    database.executebatch(b);      
    }
}
Code covergae is only 17%. The entire execute method (highlighted in bold is not covered). 
Any suggestions?
is working here 
 cancel: function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire();
    }

but not here  
 save: function(component, event, helper) {
        
        var action = component.get("c.updateAccRecordType");
        action.setParams({
            "accid": component.get("v.recordId")                   
        });
       
        $A.enqueueAction(action);
      $A.get("e.force:closeQuickAction").fire();
          $A.get('e.force:refreshView').fire();
 

       
    },
  • March 12, 2019
  • Like
  • 0
We are using REST api to update records in an external system from Salesforce.  We can update records but how do we delete records that are deleted in salesforce?  Thanks in advance for any help.
Based on my previous learnings about auto merging duplicate accounts, I set to write code to merge contacts. 
I tested each line in developer console, it works. Of course the code is not robust and has several flaws but i will get there!  

my question is , Can someone review my code and provide constructive feedback. 
Thanks!
// Created DuplicateRule for Contacts in Setup based //on standard matching rule. 
//From the DuplicatedRecordSet, fetching all //DuplicateRecordItems, which are the duplicate //Contacts.

global class DuplicateContactMergeBatch implements Database.Batchable<sObject> {

	global Database.QueryLocator start(Database.BatchableContext bc){
       // collect the batches of records or objects to be passed to execute. 
       // DuplicateRecordSet is a list of Contacts (Duplicate RecordItems) idenified as Duplicates by the Duplicate Rule
    	
		string conduplicateruleid;
		list<DuplicateRulesId__c> cs = [select id, ContactDuplicateRuleId__c from DuplicateRulesId__c limit 1];
		if(cs!=null && cs.size() > 0 ){
			for(DuplicateRulesId__c custsetting: cs){
				
			   conduplicateruleid = custsetting.ContactDuplicateRuleId__c;
				system.debug('++++++++++++++++++    ' +conduplicateruleid);
			 }
		}

		// Fetch Id and Name of the Duplicate Record Set 

		return Database.getQueryLocator([
                SELECT id, name 
                FROM DuplicateRecordSet
                Where DuplicateRuleId = :conduplicateruleid 
            ]);  
		
    }
	
	global void execute(Database.BatchableContext BC, List<DuplicateRecordSet> scope) {
              
       //call MergeAccounts method to process each batch of records
        MergeContacts(scope); 
        
    }

	public static void  MergeContacts(List<DuplicateRecordSet> dupset){
	
		//iterate through each DuplicateRecordSet, and create a map of duplicaterecordset<Id, DuplicateRecordSet> 
		Map<Id, DuplicateRecordSet> mapDuplicateRecordSet =  new Map<Id,DuplicateRecordSet>();

		if(dupset!=null && dupset.size()>0){
			for(DuplicateRecordSet drs : dupset){
				mapDuplicateRecordSet.put(drs.Id, drs);
			}
		}
		system.debug('map of duplicate record set' +mapDuplicateRecordSet);
		Map<Id, Set<Id>> mapDuplicateRecordItem =  new Map<Id, Set<Id>>();
		for(DuplicateRecordItem drI : [SELECT Id,RecordId, DuplicateRecordSetId 
									   FROM DuplicateRecordItem 
									   where DuplicateRecordSetId IN :mapDuplicateRecordSet.keyset()]){
					
					System.debug('Duplicate record Items: ' +drI);
					if(drI!=null && !mapDuplicateRecordItem.containskey(drI.DuplicateRecordSetId)){
						mapDuplicateRecordItem.put(drI.DuplicateRecordSetId, new Set<Id>{drI.RecordId}); 
					}
					else{
						mapDuplicateRecordItem.get(drI.DuplicateRecordSetId).add(drI.RecordId); 
					}
		} 

		// create a list of contacts that need to be merged 
		list<id> lstContactId = new list<id>(); 
		Set<Id>  setContactId = new set<id>();
		list<contact> mastercontact = new list<contact>();

		// iterate through all DuplicateRecordSet records that has child records 
		for(DuplicateRecordSet dr : [SELECT Id 
									 FROM DuplicateRecordSet 
									 where Id IN : mapDuplicateRecordItem.keyset()]){
			
			// Collect all disctinct contacts from the duplicaterecorditems
			setContactId =  mapDuplicateRecordItem.get(dr.Id);
			system.debug('The elements in the setofid are :' +setContactId.size());
			system.debug('Each of these elements is :' +setContactId);                             
										 
		}

		for(Contact con : [SELECT Id, lastname,email, ownerid,phone 
							   FROM Contact 
							   WHERE Id In : setContactId 
							   order by CreatedDate DESC LIMIT 1]){		
													   
							   IF(con!=null){
								mastercontact.add(con);
							   }
							   setContactId.remove(con.Id);  
							   lstContactId.addAll(setContactId);  
		}

		system.debug('master contact ' +mastercontact[0]);
		system.debug('new elemensts in the setContactId' +setContactId);
		system.debug('list of dupicated contacts ' +lstContactId);

		if(mastercontact.size()>0 && mastercontact!=null){
			try{
				Database.merge (mastercontact[0],lstContactId, true);
			}	catch (DmlException e) {
				// Process exception
				System.debug('An unexpected error has occurred: ' + e.getMessage()); 
			} 
		}
	
	}

	global void finish(Database.BatchableContext bc){
       // execute any post-processing operations
    }   

}

 
This apex sharing class - will provide read only access to previous lead owner and full access to current lead owner when lead ownership is changed. separate update trigger is written 

public class LeadRecordSharingHelper {
    public static void leadRecordShare(Map<Id, Lead> lmap, List<Lead> llist) 
    {  
        Id profileId = userinfo.getProfileId();
        String profileName = [Select Id,Name from Profile where Id=:profileId].Name;
        if (profileName == 'XXX')
        {
                        
            List<LeadShare> leadsharelist = new List<LeadShare>();
            for (Lead ld : llist)
            {
                if (ld.ownerId != lmap.get(ld.Id).ownerId)
                {                               
                    LeadShare lshare = new LeadShare();
                    lshare.LeadAccessLevel = 'Read';
                    lshare.LeadId = ld.Id;
                    lshare.UserOrGroupId = lmap.get(ld.Id).ownerId;
                    lshare.RowCause = Schema.LeadShare.RowCause.Manual;  
                    leadsharelist.add(lshare);
                }
            }     
            insert leadsharelist;
        
        }  
    }
}

We have the following record type for Accounts:

Holding Company
Main Agency
Local Agency
Advertiser

What we need is a validation rule that allows only the System Administrator to EDIT those record types? Hhow do I write this rule?

 

global class LoanOfficerBatch implements Database.Batchable<sObject> {
    public String query = 'SELECT Loan_Officer_1a__c,Loan_Officer_1a__r.Email, Name, Phone, Starting_Credit_Score__c, ' 
                          +  'Status, Enrolled_On__c, Est_Re_Pull_Date__c, Realtor_Name__c ' 
                          +   ' FROM Lead';
    public EmailTemplate templateId = [Select Id,HtmlValue,Subject from EmailTemplate where name = 'LoanOfficerRecord' LIMIT 1];

    global Database.QueryLocator start(Database.BatchableContext bc) {

        query += ' WHERE CreatedDate >= LAST_MONTH AND CreatedDate <= THIS_MONTH AND Loan_Officer_1a__c != null';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, list<Lead> allLeads) {
        Map<Id,List<Lead>> leadMap = new Map<Id,List<Lead>>();
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMEssage>();
        if(allLeads != null && allLeads.size() > 0){
            for(Lead l: allLeads){
                if(!leadMap.containsKey(l.Loan_Officer_1a__c)){
                    leadMap.put(l.Loan_Officer_1a__c, new List<lead>());
                }
                leadMap.get(l.Loan_Officer_1a__c).add(l);
            }
        }
        if(leadMap.keySet().size() > 0){
            Map<Id,Contact> officers = new Map<Id,Contact>([SELECT Id,Email,Name FROM Contact WHERE Id IN: leadMap.keySet()]);
            for(Id i: leadMap.keySet()){
                Contact con = officers.get(i);
                System.debug(con);
                if(String.isnOtBlank(con.Email)){
                    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                    mail.setToAddresses(new String[]{con.EMail});
                    mail.setSubject(templateId.Subject);
                    String html = templateId.HtmlValue;
                    html = html.replace('||OfficerName||',con.Name);
                    String leadsTable = '<table cellpadding="3" cellspacing="3" width="100%" align="center" border="1" style="border-collapse:collapse;">'+
                        '<tr style="font-weight:bold;"><td>Name</td><td>Phone</td><td>Starting Credit Score</td><td>Status</td><td>Enrolled On</td><td>Est. Re Pull Date</td><td>Realtor Name</td></tr>';
                    for(Lead l: leadMap.get(i)){
                        leadsTable += '<tr><td>'+l.Name+'</td>'+
                            '<td>'+l.Phone+'</td><td>'+l.Starting_Credit_Score__c+'</td><td>'+l.Status+'</td><td>'+l.Enrolled_On__c+'</td>'+
                            '<td>'+l.Est_Re_Pull_Date__c+'</td><td>'+l.Realtor_Name__c+'</td></tr>';
                    }
                    leadsTable += '</table>';
                    html = html.replace('||Leads||',leadsTable);
                    html = html.replace('null',' ');
                    mail.setHTMLBody(html);
                    mails.add(mail);
                }
            }
        }
        if(mails.size() > 0){
            //Messaging.sendEmail(mails);
        }
    }

    global void finish(Database.BatchableContext BC) {

    }
   
}

I'm tring to write test class following is the test class;
@isTest
private class LoanOfficerBatchTest {

	static testMethod void exTest1(){
		
		
		 Date startDate = Date.today().addMonths(-1);
        startDate = Date.newInstance(startDate.year(),startDate.month(),1);
        Date endDate = startDate;
        Integer days = Date.daysInMonth(endDate.year(), endDate.month());
		
		Contact c   = new Contact();
       c.FirstName = 'Stephen';
       c.LastName  = 'Curry';
       c.Email     = 'stephcurry@gsw.com';
       insert c;
	   
		Lead ls =new Lead(Company = 'JohnMiller', LastName = 'Mike', Status = 'Open' ,Loan_Officer_1a__c =c.Id);
		insert ls ;
		Test.setCreatedDate(ls.Id, startDate);

		
		Lead ls1 =new Lead(Company = 'JohnMiller', LastName = 'Mike', Status = 'Open' );
		insert ls1 ;
		Test.setCreatedDate(ls1.Id, startDate);

	test.startTest();

	
		test.stopTest();
	}
}

I'm not covering a code coverage of 75%. It is not increasing more than 17% please suggest. 
Hi, I'm using Talend as a development plateform, I use the Saleforce objects to do an UPSERT on the module ACCOUNT and I'm getting the error above for 3000 out of 370,000 rows. I don't do any queries, the object is doing everything for me. What would be the problem here?

Thank you for your help.

Folks,

I'm configuring a toast and I need to pass the controller's text to the <h2> tag of the view of the lightning component

TestAlert.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:actionOverride,lightning:backgroundUtilityItem" access="GLOBAL" controller="AlertController">   

<aura:attribute name="Alert" type="Alert__c" default="{'sobjectType': 'Alert__c',
                         'Tipo_de_Alerta__c': '',
                         'Name': '',
                         'Alerta1__c': ''
                          }"/>
    
    
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
<div class="demo-only" style="height: 4rem;">
	<div class="slds-notify_container slds-is-relative">    
		<div aura:id="alerta" role="status"> 
			<div  class="slds-notify__content">
                
<h2 class="slds-text-heading_small ">	Alert message here		</h2>
    
<lightning:buttonIcon iconName="utility:close" variant="bare" alternativeText="Close"
 iconClass="{!v.type == 'warning' ? 'light' : 'dark'}" size="small"
 class="slds-button slds-button_icon slds-notify__close slds-button_icon-inverse"
 onclick="{!c.close}"/>      
    
			</div>
		</div>
	</div>
</div>

    
</aura:component>

Controller.js
doInit : function(component, event, helper)
    {

          
  var tipoAlerta = component.find( "alerta" );
        
  $A.util.addClass( tipoAlerta, "slds-notify" );
  $A.util.addClass( tipoAlerta, "slds-notify_toast" );      
  $A.util.addClass( tipoAlerta, "slds-theme_success" );    


//Code to pass text to view in tag <h2> </h2>
}
I am deploying a new trigger. And It is failing. I am not a developer so I do not know how to correct the error. Any help would be appreciated. Here is the Apex Test Failuers error:

User-added image
The "TestClass" code is: 
 
@isTest(SeeAllData=true)
private class TestClass {

    static testMethod void myUnitTest() {
        Profile p = [Select id from Profile where Name ='System Administrator']; 
        Profile EUP = [Select id from Profile where Name ='EU - Standard User w/ Reporting'];
        user u = [select id, ProfileId, UserRoleId,Name, Team__c, Territory__c, Region__c from User where /*Name =: 'Gavin Barber']; //*/ProfileId =: EUP.Id and isActive = true limit 1]; //
        user u2 = [select id, ProfileId, UserRoleId,Name, Team__c, Territory__c, Region__c from User where /*Name =: 'Amy Harrington'];//*/ProfileId =: p.Id and isActive = true limit 1]; //
        
         /*User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');*/
        Date d = System.Today(); 
                
        DateTime dt = system.now();
        date flightstart = date.valueof(dt.addMonths(-3));
        date flightend = date.valueof(dt.addMonths(3));
        string ThisWeek1 = dt.format('w');
        string LastWeek = dt.addDays(-7).format('w');
        integer Lastweeki = integer.valueof((string)Lastweek);
        integer thisweeki = integer.valueof((string)thisweek1);
        string thisyear = dt.format('yyyy');
        string thisMonth = dt.format('MMMM');
        string Quarter = ThisMonth == 'January' ? 'Q1' : ThisMonth == 'February' ? 'Q1' : ThisMonth == 'March' ? 'Q1' : ThisMonth == 'April' ? 'Q2': ThisMonth == 'May' ? 'Q2' : ThisMonth == 'June' ? 'Q2' : ThisMonth == 'July' ? 'Q3' : ThisMonth == 'August' ? 'Q3' : ThisMonth ==  'September' ? 'Q3' : ThisMonth ==  'October' ? 'Q4' : ThisMonth == 'November' ? 'Q4' : ThisMonth == 'December' ? 'Q4' : '' ;
            list<Quota__c> qtalist = new list<Quota__c>();
            Quota__c testqta = new Quota__c (OwnerId = u2.Id, January__c = 100, February__c = 100, March__c = 100, April__c = 100, May__c = 100, June__c = 100, July__c = 100, August__c = 100, September__c = 100, October__c = 100, November__c = 100, December__c = 100, RecordTypeId = '012500000009iOD',Year__c = '2013',Region__c = 'aaa',Office__c = 'aaa',Team__c = 'aaa');
                qtalist.add(testqta);
            Quota__c qta3 = new Quota__c (OwnerId = u2.Id, January__c = 2, February__c = 2, March__c = 2, April__c = 2, May__c = 2, June__c = 2, July__c = 2, August__c = 2, September__c = 2, October__c = 2, November__c = 2, December__c = 2, RecordTypeId = '012500000009iOD',Year__c = '2012',Region__c = 'aaa',Office__c = 'aaa',Team__c = 'aaa');
                qtalist.add(qta3);
            Quota__c qta2 = new Quota__c (name ='default',OwnerId = u2.Id, January__c = 2, February__c = 2, March__c = 2, April__c = 2, May__c = 2, June__c = 2, July__c = 2, August__c = 2, September__c = 2, October__c = 2, November__c = 2, December__c = 2, RecordTypeId = '012500000009iOD',Year__c = '2012',Region__c = 'aaa',Office__c = 'aaa',Team__c = 'aaa');
                qtalist.add(qta2);
            insert qtalist;
         test.startTest();
            list<Account> AdvertiserList = new list<Account>();
            id holdingcompanyrt = utils.getRecordTypeId('Account', 'Holding Company');
            Account HoldingCompany =    new Account(Name = 'Test HoldingCompany', RecordTypeId = holdingcompanyrt, OwnerID = u2.Id);
                insert HoldingCompany;
            id mainagencyrt = utils.getRecordTypeId('Account', 'Main Agency');  
            Account MainAgency = new Account(Name = 'Test Main Agency', RecordTypeId = mainagencyrt,OwnerID = u2.Id,Holding_Company_Name__c = HoldingCompany.Id);  
                insert MainAgency;   
            id LocalAgencyrt = utils.getRecordTypeId('Account','Local Agency');
            Account LocalAgency = new Account(Name = 'Test Local Agency', RecordTypeId = LocalAgencyrt, Main_Agency__c = MainAgency.Id, Holding_Company_Name__c = HoldingCompany.Id, SageID__c ='ABC100');
                insert LocalAgency;
            Account LocalAgency2 = new Account(Name = 'Test Local Agency2', Main_Agency__c = MainAgency.Id ,RecordTypeId = LocalAgencyrt, SageID__c ='ABC100');
                insert LocalAgency2; 
            id Advertiserrt = utils.getRecordTypeId('Account', 'Advertiser');
            Account Advertiser = new Account(Name = 'Test Advertiser', RecordTypeId = Advertiserrt, Local_Agency__c = LocalAgency.Id );
                insert Advertiser;
                Advertiser.BillingState = 'Idaho';
                Advertiser.BillingCountry = 'United States';
                Advertiser.Create_Sage__c = true;
                Advertiser.SageID__c = '';
                Advertiser.Main_Agency__c = null;
                    update Advertiser;  
                Advertiser.BillingState = '';
                    update Advertiser;
                Advertiser.SageID__c ='100ABC';
                    update Advertiser;  
           test.stopTest();
            
                    
    }
    static testmethod void testmethod2() {
        test.startTest();   
        Opportunity opp = [select id from Opportunity where Name IN('test') and CloseDate >: system.today()-60 and Sales_Stage_High_Level__c =: 'Open' and HasOpportunityLineItem =: true limit 1];
         
            opp.move_all_flight_dates__c = true;
            opp.ContractStartDate__c = system.Today();
            opp.ContractEndDate__c = system.Today()+90;
            update opp;
        test.stopTest();
    }       
    static testmethod void testmethod5() {
        test.startTest();    
        Opportunity opp = [select id from Opportunity where Name IN('test') and Sales_Stage_High_Level__c =: 'Open' and HasOpportunityLineItem =: true limit 1];

            opp.StageName = 'Closed Won';
            opp.HasSageID__c = false;
            opp.Exception__c = false;
            opp.SVP_Email__c = null;
            
            update opp;
            delete opp;
        test.stopTest();
    }       
    static testmethod void testmethod4(){
        test.startTest();
        Opportunity opp = [select id from Opportunity where Name IN('test') and Sales_Stage_High_Level__c =: 'Open' limit 1];
        OpportunityTeamMember ot = new OpportunityTeamMember(UserId = '005500000018PC2', TeamMemberRole='Account Manager',Split__c = 50,Date_Split_Starts__c = system.Today(),Date_Split_Ends__c=system.Today()+30, OpportunityId = opp.Id);
            insert ot;
        test.stopTest();
    }
    static testmethod void testmethod6(){
         test.startTest();  
       /*    Opportunity opp = [select id from Opportunity where Name IN('test') and Sales_Stage_High_Level__c =: 'Open' and HasOpportunityLineItem =: false limit 1];
           Product2 prod = new Product2(name='test product',CanUseRevenueSchedule=True);
                insert prod;  
           PricebookEntry pbe = new PricebookEntry(UnitPrice=0, UseStandardPrice=true,Product2Id=prod.id, Pricebook2Id = '01s50000000IJr3',IsActive=true);
                insert pbe;                 
           OpportunityLineItem oliUS = new OpportunityLineItem(UnitPrice=0,Quantity=1,PricebookEntryId=pbe.Id ,OpportunityId=opp.id, Placement__c = 'aaa', Flight_Start_Date__c =system.today()-1,Flight_End_Date__c = system.today()+30, Rev_Type__c = 'CPM',Rate__c = 1, insertbudget__c = 600, distribute_evenly__c = true );
                 insert oliUS;*/
         test.stopTest();
    }
    
    static testmethod void testmethod3(){
        PageReference pageref = new Pagereference('apex/Account_Transfer2');
        test.setcurrentpage(pageRef);
        
        //Instantiate the standard controller
        Account act = new Account();
        ApexPages.StandardController sc = new Apexpages.standardController(act);
        
        //Instantiate the extension
        //Account_Transfer2 ext = new Account_Transfer2(sc);
        
        //Do the work
        //ext.getEmps();
        //ext.del();
        //ext.onSave();
        //ext.AccountWork();
        //ext.NextPage();
        //ext.Opportunity_Transfer();
    }
    
}

 
Hi  need help on creating test class for the code below: 
public static void copyContactMailingAddress(List<Account> acctList, Map<Id, Account> oldAcctMap){
        //Returns all new keys contain in the oldAcctMap
        Set<Id> acctNewId = Trigger.newMap.keyset();
        for (Account acct : acctList){
            Account oldAcctRecord = oldAcctMap.get(acct.Id);
            //Query all contactRecords with their mailing address
            List<Contact> contactRecord = [SELECT id, accountId, MailingStreet, MailingCity, MailingCountry, MailingPostalCode, MailingState
                                           FROM Contact
                                           WHERE accountId in : acctNewId]; 
            
            //Compare values from old to new billing address.
            for (Contact con : contactRecord) {   
                if (oldAcctRecord.BillingStreet != acct.BillingStreet
                   || oldAcctRecord.BillingCity != acct.BillingCity
                   || oldAcctRecord.BillingState != acct.BillingState
                   || oldAcctRecord.BillingPostalCode != acct.BillingPostalCode
                   || oldacctRecord.BillingCountry != acct.BillingCountry){
                    con.MailingStreet = acct.BillingStreet;
                    con.MailingCity = acct.BillingCity;
                    con.MailingState = acct.BillingState;
                    con.MailingPostalCode = acct.BillingPostalCode;
                    con.MailingState = acct.BillingCountry;
                }
           }
            //DML Statement to update the Billing Address that is in the Account to all related contacts
            update  contactRecord;
        }       
    }

The trigger is in before update, already have test factory for this:
@isTest
public TestDataFactory{
public static List<Account> createAcctWithCon(Integer numAcct, Integer numConPerAcct){
        List<Account> acct = new List<Account>();
        
        for(Integer i = 0; i < numAcct; i++){
            Account a = new Account(Name = 'Test Account' + i);
            acct.add(a);
        }
        insert acct; 
        
        List<Contact> con = new List<Contact>();
        for(Account at : acct){
            for(Integer j = 0; j < numAcct; j++){
                con.add(new Contact (LastName = at.Name + 'Contact' + j, AccountId = at.Id));
            }
        }
        insert con;
        return acct;
    }
}

Much need help thank you!
I am getting only the below generice error message in lightning:RecordForm compoennt

An error occurred while trying to update the record. Please try again.

But I see the below error in the onerror event parameter.

"message":"An error occurred while trying to update the record. Please try again.","detail":"","output":{"errors":[],"fieldErrors":{"Name":[{"constituentField":"LastName","duplicateRecordError":null,"errorCode":"REQUIRED_FIELD_MISSING","field":"Name","fieldLabel":"Last Name","message":"Required fields are missing: [LastName]"}]}}

Also the required fields astrerik is not appearing next to the requied fields 
Hi,

We are getting the below error when updating the record using inline edit.
Error Message
We have a before insert trigger on ContentDocumentLink which updates the Attachment checkbox to true when a file is attached to the record.

Is there any way or work around to prevent this message from showing or automatic refresh of the record when the trigger updated the record?
Here is what i tried
apex class:
public with sharing class SolutionWrapper {
    public ApexPages.StandardSetController controller;
    public Opportunity opp{get; set;}
    public Solutions__c oppId{get; set;}
    public Solutions__c sol{get; set;}
    public Solutions__c solution{get; set;}
    public Account acc{get; set;}
  
    public SolutionWrapper(ApexPages.StandardSetController controller) {
        try{
            solution = new Solutions__c();
            solution = (Solutions__c)controller.getRecord();
            if(solution.Id != null){
                oppId = [SELECT id, Solutions__c.Opportunity__c 
                    FROM Solutions__c
                WHERE id =: solution.Id
                LIMIT 1];
                
                opp = [Select id,Name, AccountId, CurrencyIsoCode  from 
                         Opportunity where id =: oppId.Opportunity__c  LIMIT: 1];
            }
            
            if(opp.id !=null){
                sol = [SELECT id,Name, Mail_Merge_Id__c,Solution_Country__c, Solutions__c.Opportunity__c 
            FROM Solutions__c
            WHERE Solutions__c.Opportunity__c =: opp.id
            LIMIT 1];
                 acc = [Select id,Name,Country__c from 
                         Account where id=:opp.AccountId LIMIT: 1];
            }
            
            
        }
        catch(Exception e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,e.getMessage()));
        }

    }

}



apex test class:
@isTest 
public class SolutionWrapperTest {

         static testMethod void testMethodOpp(){
             Account acc = new Account(Name='test', Country__c='test'); 
              insert acc; 
             Opportunity opp = new Opportunity(Name='test', AccountId=acc.id, CurrencyIsoCode='GBP', StageName = 'Good',
              CloseDate =  date.today());
             insert opp;
             Solutions__c sol = new Solutions__c( Opportunity__c= opp.id, CurrencyIsoCode='GBP');       
               insert sol;          
             
             List<Solutions__c> listSol = new List<Solutions__c>();
             listSol.add(sol);
             PageReference pageRef = Page.NewVisualForcePage;
             Test.setCurrentPage(pageRef); 
             
            Test.startTest();
             ApexPages.StandardSetController stdController = new ApexPages.StandardSetController(listSol);
             SolutionWrapper testSolution = new SolutionWrapper(stdController);
            Test.stopTest();

            }
        
        
    }
 
  • March 19, 2019
  • Like
  • 0
Hi,

  Can   anybody share any links or code regarding on creating funnel chart in lightning component?
 
I have an email action set up for cases. I would like to autopopulate with a specific email addres when sending an email from a case record. How is this achivebale?

Hi all, 

I have a working Visualforce email template, but it lists all the contacts associated to an account rather than just contacts that have a value in the role field. 

Is there a way to filter the related records to just look at contacts with roles? Below is my code!


<messaging:emailTemplate subject="Opportunity has been won, please review roles for this account" recipientType="User" relatedToType="Account">
<messaging:htmlEmailBody >
<html>
<body>
<STYLE type="text/css">
               TH {font-size: 11px; font-face: arial;background: #CCCCCC; border-width: 1;  text-align: center } 
               TD  {font-size: 11px; font-face: verdana } 
               TABLE {border: solid #CCCCCC; border-width: 1}
               TR {border: solid #CCCCCC; border-width: 1}
         </STYLE>
                  <font face="arial" size="2">
        <p>Hello,</p>
        <p>{!relatedTo.Name} has closed won opportunities. Please review the contacts with roles related to this account.</p>
        <p><u>Account Information</u></p>
        <b>Account Name:</b> <a href="https://na32.salesforce.com/{!relatedTo.id}">{!relatedTo.name}</a>  
        <br/><b>Account Owner:</b> {!relatedTo.owner.name}
        <p/>                  
       <table border="1px" >
                 <tr > 
                     <th>Contact Name</th> <th>Role</th>
                  </tr>
    <apex:repeat var="contact" value="{!relatedTo.Contacts}">
       <tr>
           <td align="center">{!contact.Name}</td>
           <td align="center">{!contact.Role__c}</td>
       </tr>
    </apex:repeat>                 
       </table>
       <p />
       <table border="1px" >
                 <tr > 
                     <th>Opportunity Name</th> <th>Amount</th>
                  </tr>
    <apex:repeat var="opportunity" value="{!relatedTo.Opportunities}">
       <tr>
           <td align="center">{!opportunity.Name}</td>
           <td align="center">{!opportunity.amount}</td>
       </tr>
    </apex:repeat>                 
       </table>
       <p />
       <p> Thank you</p>
 </font>
       
        </body>
    </html>
</messaging:htmlEmailBody> 
</messaging:emailTemplate>


Thanks so much for your help!
Tasia

Hello All,
How to disable the Help& Training, Support & Global Actions etc using Profiles in lightning?
User-added image
Regards,
VSK98
  • March 18, 2019
  • Like
  • 0
is it possible to create new field of  multipicklist value in Outlook and do a sync with salesforce multipicklist value
I am trying to cover the positive scenario of a class but i am receiving assetion fail error. Kindly help

Class:
 public class CTICallInitiationService {
 public static Id createServiceSessionRecord(String route, String callFrom, String customerType, String language, String branchPhone, String highestAuth, String trustedPhone){
        Service_Session__c serviceSessionRecord = new Service_Session__c(); 
        //serviceSessionRecord.Account_ID__c = accountId;
        serviceSessionRecord.Session_Type__c = 'Phone';        
        serviceSessionRecord.Highest_Authentication_Level_Achieved__c = highestAuth;       
        serviceSessionRecord.Authentication_Level__c = highestAuth;
        //serviceSessionRecord.Parent_Case__c=idCase;
        serviceSessionRecord.Created_Date_Time__c = System.now();
        serviceSessionRecord.Status__c = 'Active';
        serviceSessionRecord.Initiating_User__c = UserInfo.getUserId();
        serviceSessionRecord.Call_Route__c = route;
        serviceSessionRecord.Call_From_ANI__c = callFrom;
        serviceSessionRecord.Customer_type__c = customerType;
        serviceSessionRecord.Language__c = language;
        serviceSessionRecord.Branch_Phone__c = branchPhone;
        serviceSessionRecord.trusted_phone__c = trustedPhone;
        try {
            insert serviceSessionRecord;
        } catch(DmlException e) {
            serviceSessionRecord.id = null;
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
        return serviceSessionRecord.id;
        }
        }
    
Test Class:

@isTest(seeAllData=false)

private class CtiCallInitiationServiceTest {

    
     @isTest
    private static void ServiceSessionRecordTest(){
        /* Positive insertion */
        Id idSession1 = CtiCallInitiationService.createServiceSessionRecord('route', 'callFrom' , 'customerType' , 'language' , 'branchPhone' , 'highestAuth' , 'trustedPhone');
           /* Negative insertion */      
        Id idSession2 = CtiCallInitiationService.createServiceSessionRecord('test', '9080942889' , 'Consumer' , 'Test' , '9080942889' , 'Full' , 'Yes');
        
        Test.startTest(); 
        system.assertEquals(False, String.isBlank(idSession1));
           system.assertEquals(true, String.isBlank(idSession2));
        Test.stopTest();
    }
    
}
  • March 18, 2019
  • Like
  • 0
Hello,
Please, I'm traying to deploy an Apex Class using change set, but I received the following error:

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Email, Phone or MobilePhone cannot be unfilled. Please, fill someone of those fields.:

The same happen to any Apex Class is going to be deployed.
Does anyone know what this is all about? How can I fix the error?

I would appreciate any help, Regards.
Hello All,

I have created the Profile & disabled all EDIT/READ permission in profile. But the lightning user can label to view the Email Template Object.
User-added imagePlease let me know how to fix the issue.

Adv thanks,
Regards,
VSK98
  • March 18, 2019
  • Like
  • 0
Can we display a dynamic picklist in a quick action? I have a quick action on Account/Opportunity object which will create a task.I would like to display accountteam or contactteam  memebers in that quick action dynamically as a picklist
Hi Experts,

Can anyone help me how out, how to the stop the triggers not to fire any profile using custom setting. Thanks in advance
I have a requirement that ananymous user who doesn't requre login to access a page, fills the details, saves to an object (custom, and it has lookup field  to contact) . For this I have done the below steps
  • Added Domain
  • Created new Site
  • Assigned the created VF page in to the list 'Site Visualforce Pages'
  • Activated the site
  • Gave perrmissions (RWA) to the custom object
But when I click on the page I got the following error
Authorization Required

You must first log in or register before accessing this page.
If you have forgotten your password, click Forgot Password to reset it.
We should directly access to the page without authorize, how can we do this?
Thanks,