• Gokula Krishnan
  • NEWBIE
  • 464 Points
  • Member since 2015
  • Certified Salesforce Developer
  • Tech Mahindra


  • Chatter
    Feed
  • 16
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 125
    Replies
Hi All,
I need help in test class.
I have written a method for external object that sync all fields when ever I add custom fields into it. I am sharing my code please help me to write a test class for this method
global class dataSourceCon extends datasource.connection{
override global List<DataSource.Table> method1() 
    {
        
        List<DataSource.Table> extObj = new List<DataSource.Table>();

        for(ext_obj1__c Obj : 
            [SELECT Id, Name, Description__c, Name_Col__c, Label_Plu__c, Label_Sin__c, 
                (SELECT Id, Name, External_Ta__c, Data_Type__c, Decimal_Places__c, Desc__c,
                    Field_Label__c, Filtera__c, Len__c, ReferenceTarFld__c, RefTo__c, Sort__c
                    FROM External_Col__r
                )
              FROM ext_obj1__c LIMIT 50
            ])
        {
            
            List<DataSource.Column> colu_Obj = new List<DataSource.Column>();
            
            // Standard fields
            colu_Obj.add(DataSource.Column.url('DisplayUrl'));
            colu_Obj.add(DataSource.Column.text('ExternalId',255));
            
            //Custom fields 
            for(Exter_Field__c cusField : Obj.External_Col__r)
            {
                
                colu_Obj.add(setupCustomFieldData(cusField));
            }

            // Table Data
            extObj.add(setupTableData(Obj, colu_Obj));  
        }

        return extObj;
    }   
}
Please help me in writing test class for this. I am new to test class and I am struggling 

Thank in Advance

 
Hi, 

We have 2 Account Record Types, Standard & Partner. I'm trying to create a simple Apex Trigger to prevent a sales rep to change the account record type from Standard to Partner if the account has related opportunities. 

I wrote this, but as I'm new to Apex I'm pretty sure it's plenty wrong. 

trigger PreventEnablePartner on Account (before update) {

For (Account acc : [SELECT Id,RecordTypeId
                    FROM Account
                    WHERE Id IN (SELECT AccountId FROM Opportunity)
                    AND RecordType.Name = 'Partner']) {
                        
Account oldAccount = Trigger.oldMap.get(acc.ID);

IF(acc.RecordTypeId != oldAccount.RecordTypeId ) {
    Trigger.New[0].addError('Cannot "Enable As Partner" an account with related opportunities.');}
    Else {Return;}
}
}

Do you have any idea ? 

Thanks,
my class ------>

public without sharing class AllBeatMaps {
   
    public list<Beat_Map__c> bmapList {get;set;}
    public list<User> salesRepList {get;set;}
    public String pageTitle {get;set;}
    public String querytype {get;set;}
   
    public AllBeatMaps(){
     pageTitle='SELECT BEAT MAP';
     String salesRep = 'Sales Rep';
     querytype = apexpages.currentPage().getParameters().get('type');
     String query1 = 'SELECT Id,Name,Beat_Definition__c FROM Beat_Map__c';
     String query2 = 'SELECT Id,Name,Userrole.Name FROM User WHERE UserRole.Name=';
     
     if(querytype!=null && querytype.trim().length()>0){
      if(querytype=='beatmap'){
       bmapList = Database.query(query1);
      }
      if(querytype=='salesrep'){
       pageTitle = 'SELECT SALES REP';
       query2+='\''+salesRep+'\'';
       salesRepList=Database.query(query2); 
      }
     }
    }
   
}

Test Class ---------->

@isTest
public class AllBeatMapsTest {
    public static testmethod void allbeatmptest(){
        profile SalesRep = [Select Id FROM Profile Where Name= 'Sales Representative'];
        userRole urp = new UserRole(Name = 'Sales Rep');
        insert urp;
        User ur = new User(UserRoleid=urp.Id,ProfileId = SalesRep.Id,Alias = 'hfsre',Country='India',Email='defo1@urturiurain.com',EmailEncodingKey='UTF-8', LastName='oiuriuterh', LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Los_Angeles', UserName='wdjhfgb@b.com');
        insert ur;
 
        system.runAs(ur){
        list<User> usa = new list<User>();
        usa.add(ur);
           
            Beat_Map__c bm = new Beat_Map__c();
            bm.Beat_Definition__c = 'Gurugram Sector 14,17,21,23';
            insert bm;
            list<Beat_Map__c> bmc = new list<Beat_Map__c>();
            bmc.add(bm);
  PageReference pageRef = Page.AllBeatMaps;
  Beat_Map__c bcc = new Beat_Map__c();
  bcc.Beat_Definition__c = 'Gurugram Sector 45,17,21,23';
  insert bcc;
  
   Test.setCurrentPage(pageRef);
   pageRef.getParameters().put('id',bcc.id);
           
            AllBeatMaps obh = new AllBeatMaps();
           
 }
}
           
          
         
           
        }
   
 
Hi,

  I have a below code which is working as expected it gives list of account names and contact name top to bottom

  Now my requirement is in contact we have NSE1 and NSE2 has two feilds  this needs to be added or sum and displayed when it is views from partner account
 
Example;  
        Account A is Top Parent  Has 1 Contacts  NSE1 = 1 and NSE2 = 1
        Account  B is Child of Account A Has 1 Contacts  NSE1= 1 and NSE2 = 1
        Account C is Child of Account B  Has 1 Contacts  NSE1= 0 and NSE2 = 1

If I see Account A Contact NSE1 and NSE2 should be NSE1 = 2 and NSE2 = 3
If I see Account A Contact NSE1 and NSE2 should be NSE1 = 1 and NSE2 = 2
If I see Account A Contact NSE1 and NSE2 should be NSE1 = 0 and NSE2 = 1

Code should display values as above. Please suggest me how to obtain this sum or add up the boolean values at parent level.
set<id> setactid = new set<id>();
    
Id accountId = '001W000000aDqeA';
        
 Account[] allparents = new Account[] {};
            
 Set<Id> parentIds = new Set<Id>{accountId};
                
 Account[] parent;
        
 do {
            
  parent = [select Id,ParentId, Name from Account where Id in :parentIds];
            
  allparents.addAll(parent);
            
  parentIds.clear();
            
  for (Account par : parent) 
                
  parentIds.add(par.ParentId);
            
  } while (parent.size() > 0);
        
  list<Account> Act = [select id, name from account where id in :allparents];
        
  for(Account A : Act){
     
    system.debug(a.name);  
     setactid.add(a.id);
           //dispaly here the sum of NSE1 and NSE2 account level grouping the contacts

      for(Contact C : [select id,name,NSE_1__c,NSE_2__c from contact where accountid in :setactid]){
        system.debug(c.name);
          system.debug('NSE_1__c   ' + c.NSE_1__c); //How to add this boolean values 
          system.debug('NSE_2__c   ' + c.NSE_2__c);
          
      }  
            
   }


Thanks
Sudhir


 
I have Object A and OBJECT B. B is the detail and A the master in a master-detail relationship
B will get records with dollar amount many times a month
On A I would like to have a total of those amounts on B but only a rolling last 12 months

Is there a way to do this without a trigger? I can total them easily but how to do the rolling 12 months?
Hello,

I want to develop functionality where mail should be send to related cases when mail sent to parent case.
How can we achive this?

Thanks & Regards,
Utkarsha
  • October 27, 2017
  • Like
  • 0
I have all participant and states object (two records registered and assessed ). for some participant is not assesed inthe table evethough it is actually assessed. need to insert those records to states as assesesd 

i have list of patticipant ids and list of  states as assessed 

 if(recs.size()>0 && participantsatates.size()>0) 
         {
              for(participant__c p:recs)
                 {
             
                     for(States__c pstate :participantsatates)
                         
                         {
                            IF (P.Id = pstate.Participant__c)
                            {
                                
                                
                            }
                             
                 
                         }
                 }
  • October 23, 2017
  • Like
  • 0
Hey guys. I'm irregularly experiencing troubles, that I suddenly cannot close won opportunities. Trying to set an opportunity 'closed won' results in the following error:

The record couldn’t be saved because it failed to trigger a flow. A flow trigger failed to execute the flow with version ID 30124000000LrED . Flow error messages: <b>An unhandled fault has occurred in this flow</b><br>An unhandled fault has occurred while processing the flow. Please contact your system administrator for more information. Contact your administrator for help.

I tried to use Mayank Srivastava's solution from this post: https://success.salesforce.com/answers?id=9063A0000019NR7QAM
However my Flow designer is completely blank - I cannot see any unsaved flows. (see screenshot)
Any suggestions what I can do?
Much appreciated!

User-added image

Here is the Error-Email Salesforce send to me 

Error element myRule_1_A1 (FlowRecordCreate).
This error occurred when the flow tried to create records: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY: OrderCreated: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INACTIVE_OWNER_OR_USER, operation performed with inactive user [00524000001RgP1] as owner of task: [] Trigger.OrderCreated: line 59, column 1. For details, see API Exceptions.

This report lists the elements that the flow interview executed. The report is a beta feature.
We welcome your feedback on IdeaExchange.

Flow Details
Flow Name: Opportunity_Won
Type: Workflow
Version: 22
Status: Active

Flow Interview Details
Interview Label: Opportunity_Won-22_Opportunity
Current User: Clemens Kemper (00524000001SVfn)
Start time: 23.10.2017 13:29
Duration: 0 seconds

How the Interview Started
Clemens Kemper (00524000001SVfn) started the flow interview.
Some of this flow's variables were set when the interview started.
myVariable_old = 0062400000Zi7uUAAR
myVariable_current = 0062400000Zi7uUAAR

ASSIGNMENT: myVariable_waitStartTimeAssignment
{!myVariable_waitStartTimeVariable} Equals {!Flow.CurrentDateTime}
Result
{!myVariable_waitStartTimeVariable} = "23.10.2017 13:29"

DECISION: myDecision
Executed this outcome: myRule_1
Outcome conditions: and
1. {!myVariable_current.IsWon} (true) Equals true
Logic: All conditions must be true (AND)

DECISION: myRule_1_pmetdec

RECORD CREATE: myRule_1_A1
Create one Order record where:
AccountId = {!myVariable_current.AccountId} (0012400000NH9v4AAD)
Ansprechpartner__c = {!myVariable_current.Ansprechpartner__c} (null)
Auf_Wasser__c = {!myVariable_current.Auf_Wasser__c} (false)
BillingCity = {!myVariable_current.Account.BillingCity} (Düsseldorf)
BillingCountry = {!myVariable_current.Account.BillingCountry} (DE)
BillingPostalCode = {!myVariable_current.Account.BillingPostalCode} (40235)
BillingStreet = {!myVariable_current.Account.BillingStreet} (Schlüterstraße 10)
EffectiveDate = {!myVariable_current.CloseDate} (23. October 2017)
Opportunity__c = {!myVariable_current.Id} (0062400000Zi7uUAAR)
Pricebook2Id = {!myVariable_current.Pricebook2.Id} (01s24000004FUmIAAW)
Rechnungsdatum__c = {!myVariable_current.CloseDate} (23. October 2017)
Status = Draft
Veranstaltungsart__c = {!myVariable_current.Veranstaltungsart__c} (Silvesterfeuerwerk)
Z_nddatum__c = {!myVariable_current.Z_nddatum__c} (31. December 2017)
Z_ndzeit__c = {!myVariable_current.Z_ndzeit__c} (0:00)
berraschung_f_r__c = {!myVariable_current.berraschung_f_r__c} (null)
ueberraschung__c = {!myVariable_current.berraschung__c} (false)
Result
Failed to create record.
I already did in previous version.. In new version Can any one help to complete checkchallenge Data Security-> Control Access to Fields?
Hello, 

I cannot find the  solution to the above mentioned issue, could you possibly have a look on line 23 and let me know you can see the flaw in my code?
User-added image

The error given by the Developer Console is: 
User-added image
Can any one spot what's wrong with line 23?
Thank you very much.
Hi,

I am getting the error: 09:59:02:052 FATAL_ERROR System.QueryException: List has no rows for assignment to SObject when trying to complete the Apex Web services challenge.

Here is my code:

a) AccountManager class:
====================

@RestResource(urlMapping='/Accounts/*/Contacts')
global class AccountManager {
    @HttpGet
    global static Account getAccount() {
        RestRequest request = RestContext.request;
        String AccId = request.requestURI.substringBetween('/Accounts/' , '/Contacts');
        Account result =  [SELECT Id, Name, (Select Id, Name from Contacts) FROM Account WHERE Id = :AccId];
        return result;
    }
}


b) AccountManagerTest:
===================
@isTest
private class AccountManagerTest {

    private static testMethod void getAccountTest1() {
        Id recordId = createTestRecord();
        System.debug('record id = ' + recordId);
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri = 'https://cunning-bear-27155-dev-ed.my.salesforce.com/services/apexrest/Accounts/'+ recordId +'/contacts' ;
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount != null);
        System.assertEquals('Test record', thisAccount.Name);
        
    }

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Account TestAcc = new Account(
            Name='Test record');
        insert TestAcc;
        Contact TestCon= new Contact(
            LastName='Test', 
            AccountId = Testacc.id);
        insert TestCon;
        return TestAcc.Id;
    }      
}
 

Below is the code coverage issu due to this not able to get required code coverage.

if you provide snippet code will highly appreciate..

User-added image
 
Hi,
I have created a task on the object Contract. There are same task types with different criterias, what i want is that if one of the same task type has a status as " Open", in the object Contract, It shouldnt generate another same type of task. I have " Type" as a picklist in the task.
May be for that it seems i need a task type counter field in the contract object ( how to do that ? ) which i can use in the PB logic or how to do that in any other way ? Thanks

Hello friends.

I'm having issue with this trigger in the Opportunity Products. It works fine in the Developer Sandbox, but it doesn't work in the Partial Sandbox or Full Sandbox... so I doubt that it will work in the production. Can you guys help me out? I tried everything...

I have the following trigger:

trigger AutoAddPF00001 on OpportunityLineItem (after insert, after update)
{
    List<OpportunityLineItem> oliList = new List<OpportunityLineItem>();

    List<String> lstProductCodes = new List<String>();

    for(OpportunityLineItem optLineItem: Trigger.new)
    {
        if(optLineItem.ProductCode == '00001a')
        {
            lstProductCodes.add(optLineItem.ProductCode);
        }
    }

    if(lstProductCodes.size()>0)
    {
        System.debug('lstProductCodes=' + lstProductCodes);

        //retrieve the values based on Product list
        List<OpportunityLineItem> lstOpptyLineItems = [SELECT OpportunityId, Opportunity.Pricebook2Id, Name, ProductCode , PricebookEntryId, Quantity, UnitPrice
                                                        FROM    OpportunityLineItem
                                                        WHERE ProductCode IN:lstProductCodes];

        //create a map which contains Product Name and OpportunityLineItem
        Map<String, OpportunityLineItem> mapOpptyLineItem = new Map<String, OpportunityLineItem>();
        for(OpportunityLineItem item:lstOpptyLineItems)
        {
            mapOpptyLineItem.put(item.ProductCode, item);
        }


        Id pbkId = lstOpptyLineItems[0].Opportunity.Pricebook2Id;

        //retrieve PriceBookEntry of the Product B, this is most important
        PricebookEntry pbeProduct2 = [SELECT Id, Pricebook2Id, UnitPrice, Name, Product_Fee_Percentage__c 
                                        FROM PricebookEntry
                                        WHERE Name ='Product Fee'
                                        AND Pricebook2Id  IN (SELECT Id FROM PriceBook2 WHERE Id =:pbkId) LIMIT 1];

        //retrieve Product A item from the map.        
        OpportunityLineItem itemProductA = mapOpptyLineItem.get('00001a');
        System.debug('itemProductA= ' + itemProductA);

        if(itemProductA != null)
        {
            if(Trigger.isInsert)
            {
            //now assign Product A items as required, you can retrieve the amount from Product A
            oliList.add(new OpportunityLineItem(
                OpportunityId = itemProductA.OpportunityId,
                PricebookEntryId = pbeProduct2.Id,
                Quantity = itemProductA.Quantity,
                UnitPrice = itemProductA.UnitPrice * pbeProduct2.Product_Fee_Percentage__c * 0.01 )
              );
            System.debug('oliList=' + oliList);
            insert oliList;
        }
        else if (Trigger.isUpdate)
            {
                //if you need to update PriceBookEntry of Product B
                pbeProduct2.UnitPrice = itemProductA.UnitPrice * pbeProduct2.Product_Fee_Percentage__c * 0.01 ;
                update pbeProduct2;

                //if you need to update OpportunityLineItem of Product B
                OpportunityLineItem optLIProductB = [SELECT OpportunityId, Opportunity.Pricebook2Id,
                                                        Name, ProductCode , PricebookEntryId,
                                                        Quantity, UnitPrice
                                                        FROM    OpportunityLineItem
                                                        WHERE ProductCode = '00001b'];

                optLIProductB.Quantity = mapOpptyLineItem.get('00001a').Quantity;
                optLIProductB.UnitPrice = mapOpptyLineItem.get('00001a').UnitPrice * pbeProduct2.Product_Fee_Percentage__c * 0.01 ;

                update optLIProductB;
            }
    }
}
}

I'm getting the following error:
Apex trigger AutoAddPF00001 caused an unexpected exception, contact your administrator: AutoAddPF00001: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject: Trigger.AutoAddPF00001: line 35, column 1

Line 35 is:
PricebookEntry pbeProduct2 = [SELECT Id, Pricebook2Id, UnitPrice, Name, Product_Fee_Percentage__c

I tried the solution given by the article below, but it causes more issues.
https://help.salesforce.com/articleView?id=000159853&type=1

So I used the following code with some help:​
List<PricebookEntry> pbeProduct2=new List<PricebookEntry>();
 pbeProduct2 = [SELECT Id, Pricebook2Id, UnitPrice, Name, Product_Fee_Percentage__c 
                            FROM PricebookEntry
                            WHERE Name ='Product Fee'
                            AND Pricebook2Id  IN (SELECT Id FROM PriceBook2 WHERE Id =:pbkId) LIMIT 1];
System.debug('pbeProduct2 '+pbeProduct2);

I get the following error if I try the solution given in the link above:
Error: Compile Error: Variable does not exist: Id at line 53 column 48

Line 53 is:
PricebookEntryId = pbeProduct2.Id,

  • October 11, 2017
  • Like
  • 0
I’m setting up an automatic “Thank You” email that will send to our donors when an opportunity closes.
The workflow rule refers to specific criteria.
Examples:
  1. IF the primary contact email IS NOT BLANK
  2. IF the opportunity is less than or equal to $250
  3. IF the stage equals “posted”
There are other criteria as well.
If a user checks the box, the email will only send to the donor IF all of the criteria have been met.
If all of the criteria hasn’t been met, I can create a workflow rule/process builder to insert a value in a new field that I’m going to create, indicating which criteria hasn’t been met.

For example:

IF “Email Permission” box is checked AND the primary contact email IS BLANK, update field to:
Primary contact email is blank
What I’m wondering is…if multiple criteria are not met – how would I know?
Maybe we can append values or maybe there’s another solution?

Thank you for your help.
 
My trigger.oldMap does not seem to return old values if the amount is changed?

Trigger:
trigger TestFunctions on Opportunity (after insert,  after update, after delete, after undelete) {
    if(checkRecursive.runOnce())
    {
    
    if(trigger.isinsert|| trigger.isundelete){
        testFuncClass1.handleInsert(trigger.new);
    }
    if(trigger.isupdate|| trigger.isdelete){
       testFuncClass2.handleupdate(trigger.newmap, trigger.oldmap);
        //system.debug('trigger.oldmap'+trigger.oldmap);
    }
        
    }     
}

Class:
public class testFuncClass2 {
    public static void handleUpdate(map<id, opportunity> updateNewOpps, map<id, opportunity>updateOldOpps){
        if(recusrssionPreventController.flag){

            for(opportunity o : [select id, amount from opportunity where id in : updateNewOpps.keySet()]) {
                system.debug(o);// returns new value
            }  
            for(opportunity o2 : [select id, amount from opportunity where id in : updateOldOpps.keySet()]) {
                system.debug(o2);// returns new value???
            }  
            system.debug(updateNewOpps);//Returns correct values
            system.debug(updateOldOpps);//Returns correct values
            
    }
    }
}

Can anyone please help?
  • October 08, 2017
  • Like
  • 0
Hi All,
I need help in test class.
I have written a method for external object that sync all fields when ever I add custom fields into it. I am sharing my code please help me to write a test class for this method
global class dataSourceCon extends datasource.connection{
override global List<DataSource.Table> method1() 
    {
        
        List<DataSource.Table> extObj = new List<DataSource.Table>();

        for(ext_obj1__c Obj : 
            [SELECT Id, Name, Description__c, Name_Col__c, Label_Plu__c, Label_Sin__c, 
                (SELECT Id, Name, External_Ta__c, Data_Type__c, Decimal_Places__c, Desc__c,
                    Field_Label__c, Filtera__c, Len__c, ReferenceTarFld__c, RefTo__c, Sort__c
                    FROM External_Col__r
                )
              FROM ext_obj1__c LIMIT 50
            ])
        {
            
            List<DataSource.Column> colu_Obj = new List<DataSource.Column>();
            
            // Standard fields
            colu_Obj.add(DataSource.Column.url('DisplayUrl'));
            colu_Obj.add(DataSource.Column.text('ExternalId',255));
            
            //Custom fields 
            for(Exter_Field__c cusField : Obj.External_Col__r)
            {
                
                colu_Obj.add(setupCustomFieldData(cusField));
            }

            // Table Data
            extObj.add(setupTableData(Obj, colu_Obj));  
        }

        return extObj;
    }   
}
Please help me in writing test class for this. I am new to test class and I am struggling 

Thank in Advance

 

HI Folks, 
Getting Debuglog Error, 

System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

Below is my Trigger:

Trigger CaseCustomer on Case (before insert,after update) {
    Try{
    Set<String> stemail = new Set<String>();
    List<Customer__c> custlst = new List<Customer__c>();
    Map<String,Customer__c> mpemailtocustomer = new Map<String,Customer__c>();
    List<Case> updcaselst = new List<Case>();
    Map<String,Entitlement> mpentitle = new Map<String,Entitlement>();
    Set<Id> casid = new Set<Id>();
    List<CaseMilestone> cmsToUpdate = new List<CaseMilestone>();
    
    if(Trigger.isAfter)
    {
        for(Case icas:Trigger.New)
        {
            if((trigger.newMap.get(icas.id).Status!= trigger.oldMap.get(icas.id).Status) && icas.Status == 'Closed')
            {
                casid.add(icas.id);
                System.debug(casid);
            }
        }
        if(casid.size()>0)
        {
            cmsToUpdate = [select Id,completionDate from CaseMilestone where caseId IN :casid];
            System.debug(cmsToUpdate);
        }
        if(cmsToUpdate.size()>0)
        {
            for(CaseMilestone icasn:cmsToUpdate)
            {
                icasn.completionDate = System.now();
            }
            update cmsToUpdate;
        }
        
    }
    
   else
   {
    for(Case icas:Trigger.New)
    {
        if(icas.SuppliedEmail != null)
        {
            stemail.add(icas.SuppliedEmail);
            System.debug(stemail);
        }
    }
    if(stemail.size()>0)
    {
        custlst = [SELECT ID,Email__c FROM Customer__c WHERE Email__c IN:stemail];
        System.debug(custlst);
    }
    if(custlst.size()>0)
    {
        for(Customer__c icus:custlst)
        {
            mpemailtocustomer.put(icus.Email__c,icus);
            System.debug(mpemailtocustomer);
        }
    
    }
    List<Entitlement> entlst = [SELECT id,Name FROM Entitlement];
    if(entlst.size()>0)
    {
        for(Entitlement ient :entlst)
        {
            mpentitle.put(ient.Name,ient);
        }
    }
    
        for(Case icas : Trigger.New)
        {
            if(mpemailtocustomer.containskey(icas.SuppliedEmail))
            {
                icas.Customer__c = mpemailtocustomer.get(icas.SuppliedEmail).ID;           
            }
            if(icas.Origin == 'Email' ||  icas.Origin == 'Phone' || icas.Origin == 'Web')
            {
                icas.EntitlementId = mpentitle.get('Response').Id;
                System.debug(icas.EntitlementId);
            }
        }
    
    }
    }catch(exception e)
    {
        System.debug(e.getlinenumber()+e.getmessage());
    }
}

Please Do help,
Thanks In Advance.
  • January 10, 2018
  • Like
  • 0
It is a simple page here is the code 
<apex:page standardController="Opportunity">
            <apex:outputField value="{! Opportunity.Name}"/>
            <apex:outputField value="{! Opportunity.Amount}"/>
            <apex:outputField value="{! Opportunity.CloseDate}" />
            <apex:outputField value="{! Opportunity.AccountName}" />
</apex:page>
What's wrong


 
Hi Team, 
I am new resource i don't know how to write test class i have written triggerhandler class on opportunity and i post the code below , can you make test class 
public class OpportunityTriggerHandler{
    public void handleTrigger (Opportunity[] trigNew){
        if (trigger.isBefore){
            if(trigger.isUpdate){
                handleBeforeInsert(trigNew);
                }
               } 
            else if (trigger.isInsert){
                handleBeforeInsert(trigNew);
                }
       }         
    public void handleBeforeInsert(Opportunity[] trigNew)
    {
        for (Opportunity objOpps : trigNew)
        {
            if ((objOpps.StageName == 'Prospecting') || (objOpps.StageName == 'Perception Analysis') || (objOpps.StageName == 'Qualification') || (objOpps.StageName == 'Needs Analysis')
                                                 || (objOpps.StageName == 'Value Proposition')||(objOpps.StageName == 'Id.Decision Markers')||(objOpps.StageName == 'Proposal/Price Quote'))
            {
               
               if ( objOpps.Win_Lose_Comment__c != null){   
                objOpps.Win_Lose_Comment__c.addError('Donfill the  value Win/Lose Comment');
                }
                
               if ( objOpps.Win_Lose_Reason__c != null){
                objOpps.Win_Lose_Reason__c.addError('Don t fill  the value Win/Lose Reason');
                }
                
                if( objOpps.Type_Lose__c != null)
                {
                objOpps.Type_Lose__c.addError('Dont fill the value Type Lose');
                }
        
            }
        
            else if ((objOpps.StageName == 'Negotiation/Review') || (objOpps.StageName == 'Closed Won'))
            {
                if ( objOpps.Win_Lose_Comment__c == null){
                       objOpps.Win_Lose_Comment__c.addError('Please select the value Win/Lose Comment'); 
                    }
                if ( objOpps.Win_Lose_Reason__c == null)
                {
               
                   objOpps.Win_Lose_Reason__c.addError('Please select the value Win/Lose Reason');
                }      
               
            }
        
            else if(objOpps.StageName == 'Closed Lost')
            {
                if ( objOpps.Win_Lose_Comment__c == null){
                        objOpps.Win_Lose_Comment__c.addError('Please fill the  value Win/Lose Comment');
                 } 
                 
                if ( objOpps.Win_Lose_Reason__c == null){
                        objOpps.Win_Lose_Reason__c.addError('Please  fill  the value Win/Lose Reason');
                 }
                 
                  if( objOpps.Type_Lose__c == null)
                {
                  
                  
                      objOpps.Type_Lose__c.addError('Please fill the value Type Lose');
                }
            
            
           // else{}
            
           }     
            
        }
    }  
}
trigger UpdateStage on Account (after insert, after update, before insert, before Update) {   // Performs Custom actions after Record gets saved.
   
    List<Id> accountId = new List<Id>(); // get the list of all Account's ID to be Updated.
    
    for(Account acc : Trigger.new)
    {
        if(acc.All_Opportunities_Won__c==True)   // Checks if the Condition is True. 
            accountId.add(acc.Id);
    }
    
    List<Opportunity> oppsToUpdate = new List<Opportunity>();
    
    for(Opportunity opp : [select id, StageName, Amount from Opportunity where AccountId in: accountId AND Amount != 0]) // used to get all records from above ID.
    {
        opp.StageName='Closed-Won';   //Update StageName in Opportunity
        oppsToUpdate.add(opp); 
    }
    
    update oppsToUpdate;   // Update all Opportunity in List.
}

 
Hi, 

We have 2 Account Record Types, Standard & Partner. I'm trying to create a simple Apex Trigger to prevent a sales rep to change the account record type from Standard to Partner if the account has related opportunities. 

I wrote this, but as I'm new to Apex I'm pretty sure it's plenty wrong. 

trigger PreventEnablePartner on Account (before update) {

For (Account acc : [SELECT Id,RecordTypeId
                    FROM Account
                    WHERE Id IN (SELECT AccountId FROM Opportunity)
                    AND RecordType.Name = 'Partner']) {
                        
Account oldAccount = Trigger.oldMap.get(acc.ID);

IF(acc.RecordTypeId != oldAccount.RecordTypeId ) {
    Trigger.New[0].addError('Cannot "Enable As Partner" an account with related opportunities.');}
    Else {Return;}
}
}

Do you have any idea ? 

Thanks,
Hi,

 Multiple users are following a case and when status of case gets changes, all users who are following case should notified throgh email.

User-added image

User-added image

Any help is really appreciated . 

Thanks,
Naveen.
 

here is the quick background:- i wrote a validation rule to restrict the picklist value on user object but there is losts of test claases are getting failed. i choose teh approach to create a helper class to create user test data then i can call. i tried to write the test class not sure it will work please help me with the good approach . how can i can my helper class into my test class

global class TestClassHelper
{    
     public User CreateUser()
    {
        //Get a profile id from the data base to assign to our user in this case make them a sys admin
        Profile p = [select id from profile where name='System Administrator'];
           
           //Create a new sys admin user and do an insert  
        User u = new User(alias = 'standt', email='noEmail@testorg.com',
                          emailencodingkey='UTF-8', lastname='Testo', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,
                          timezonesidkey='America/Los_Angeles', username='MrTestUser@testorg.com',Resource_Type__c='Employee');
                          
        User u1 = [Select u.Profile.Name, u.ProfileId, u.Name, u.Id From User u where u.Profile.Name = 'System Administrator' limit 1];
                          
        return u;
    }
    
    public User CreateUser(string userType)
    {
        //Get a profil id from the data base to assign to our user in this case make them a sys admin
        Profile p = [select id from profile where name=:userType];
           
           //Create a new sys admin user and do an insert  
        User ur = new User(alias = 'standt', email='noEmail@testorg.com',
                          emailencodingkey='UTF-8', lastname='Testo', languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id,
                          timezonesidkey='America/Los_Angeles', username='MrTestUser@testorg.com',Resource_Type__c='Employee');
           return ur;
    }
}


how can i call both method in my test class.

user u = TestClassHelper.CreateUser();?

i am not sure how i can call  public User CreateUser(string userType)
user u = TestClassHelper(---) ,what should be argument ?..this is my helper class do i need 2  methods?



 
could you please help me to create test class for the below code, as mock test response need to create here, and iam new for this.
here the intraction between web application and salesforce is happning,
getting input from web application to update the record having valid recordID. 
@RestResource(urlMapping='/LeadRestUpdate/*')

Global with sharing class  NS_WS_Lead_update {
    @HttpPost
    Global static String doUpdate()
    {
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        System.debug('Params: ' + req.params);
        //String temp = req.requestBody.toString();
        String leadid = req.params.get('lead_id');
        Lead ll = [SELECT Id, FirstName,LastName, Phone, email, company FROM Lead WHERE Id = :leadid];
        if (req.params.get('step') == 'step1' || req.params.get('step') == 'step2' )
        {
            ll.FirstName = req.params.get('first_name');
            ll.LastName = req.params.get('last_name');
            ll.phone = req.params.get('phone');
            ll.Email = req.params.get('email');
            ll.Company = req.params.get('company_name');
            ll.Company_Registration_Number__c = req.params.get('registration_number');
            ll.Company_Status__c = req.params.get('company_status');
            ll.CompanyType__c = req.params.get('company_type');
            if(req.params.get('incorporated_date') != null && req.params.get('incorporated_date') != '' ) {
                ll.Incorporation_Date__c = Date.valueOf(req.params.get('incorporated_date'));
            }
            ll.Street = req.params.get('street');
            ll.City = req.params.get('city');
            ll.State = req.params.get('state');
            ll.Country = req.params.get('country');
            ll.PostalCode = req.params.get('zip');
            
        }
        if (req.params.get('step') == 'step2')
        {
            ll.Industry = req.params.get('industry');
            if(req.params.get('take_card_payment') == 'true')
               {
                ll.Do_you_take_Card_transactions__c = Boolean.valueOf( req.params.get('take_card_payment'));
                ll.Average_monthly_card_takings__c = req.params.get('cardtakings_amount');
                ll.Average_monthly_takings_4_200__c = Boolean.valueOf( req.params.get('cardtakings'));
                ll.Average_monthly_transactions_10__c = Boolean.valueOf( req.params.get('cardtransaction10andmore'));
            }
        }
        if (req.params.get('step') == 'step3')
        {
            Double amount_requested =  Double.valueOf(req.params.get('amount_requested'));
            ll.Amount_Requested__c = amount_requested;
            ll.Term_Requested__c  = Double.valueOf(req.params.get ('loan_term'));
            ll.Purpose_of_Facility__c = req.params.get('puropose_of_funding');
        }
        if (req.params.get('step') == 'step4')     
        {
            //ll.Web_to_Lead__c = Boolean.valueOf(req.params.get('web_to_lead'));
            ll.Residential_Address_City__c = req.params.get('residential_city');
            ll.Residential_Address_Country__c = req.params.get('residential_country');
            ll.Residential_Address_State_Province__c = req.params.get('residential_state');
            ll.Residential_Address_Street__c = req.params.get('residential_street');
            ll.Residential_Address_Zip_Postal_Code__c = req.params.get ('residential_zip');
            if (req.params.get('product_interested') != 'bca') {
                ll.Home_Owner__c = Boolean.valueOf(req.params.get('own_a_property'));
                ll.Ownership_is_of_Residential_Address__c = Boolean.valueOf(req.params.get('same_as_residency'));
                ll.Property_Address_City__c = req.params.get('property_city');
                ll.Property_Address_Country__c = req.params.get('property_country');
                ll.Property_Address_State_Province__c = req.params.get('property_state');
                ll.Property_Address_Street__c = req.params.get('property_street');
                ll.Property_Address_Zip_Postal_Code__c = req.params.get('property_zip');
            }
            if (req.params.get('allow_credit_search') == 'true')
                ll.Allow_searches_on_all_directors__c = Boolean.valueOf( req.params.get('allow_credit_search'));  
            else
                ll.Allow_searches_on_all_directors__c = false;
            if(req.params.get('allow_engaging_card_provider')!=null)
               {
                ll.Authorization_to_contact_card_provider__c = Boolean.valueOf( req.params.get('allow_engaging_card_provider'));
            }
            if(req.params.get('take_card_payment') == 'true')
               {
                ll.Do_you_take_Card_transactions__c = Boolean.valueOf( req.params.get('take_card_payment'));
                ll.Average_monthly_card_takings__c = req.params.get('cardtakings_amount');
                ll.Average_monthly_takings_4_200__c = Boolean.valueOf( req.params.get('cardtakings'));
                ll.Average_monthly_transactions_10__c = Boolean.valueOf( req.params.get('cardtransaction10andmore'));
            }
        }
        update ll;
        string messagesent='Thank You. Salesforce has Successfully Updated'+ll.id+req.params.get('step');
        return messagesent;
    }
}
Could anyonehelp me to create test class for below, iamnot getting the expected test coverage.

@RestResource(urlMapping='/LeadRestGet/*')

global with sharing class NS_WS_Lead_Insert {
    @HttpGet
    global static Lead doGet() {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;
        //String leadId = req.params.get('existing_lead_id');
        String leadId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        Lead result = [SELECT Id, FirstName, LastName, phone, Email, Company,  Lead_Source_Information__c,
         Authorization_to_contact_card_provider__c          
        FROM Lead WHERE Id = :leadId];
        return result;
        
    }
    
    @HttpPost
    global static String doPost()
    {
        RestRequest req = RestContext.request;
        RestResponse res = Restcontext.response;
        System.debug('Params: ' + req.params);
        //String temp = req.requestBody.toString();
        Lead ll = new Lead();
        ll.FirstName = req.params.get('first_name');
        ll.LastName = req.params.get('last_name');
        ll.phone = req.params.get('phone');
        ll.Email = req.params.get('email');
        ll.Web_to_Lead__c = Boolean.valueOf(req.params.get('web_to_lead'));
        //if (req.params.get('web_to_lead') == 'true'){
        //    ll.Web_to_Lead__c = true;
        // }
               
        string messagesent;     
         try {
            insert ll;
        }
        catch (DMLException e)
        {
            messagesent=e.getMessage();
        }
        if(messagesent==null)  
        {
            messagesent=ll.id;
        }
        return messagesent;
    }
}
If Account has 10 Contacts then in Contact checkbox field inactive then the account checkbox also inactive ?(primary account) how to create trigger?
 
Hi all,
 
I'm looking for a way to populate the sum of Events related to an Account (number of visits), over a period of time, probably fiscal year, and display this field on the Account Layout.
How would I be able to do that ? Roll-up summary, Trigger ? My dev skills are quite limited. 
 
Thanks a lot.
I'm trying to get OpportunityContactRoleId while creating new Opportunity to Contact.

If I'm using Salesforce Classic, the following example works fine.
But if I switch to Lightning, I got error "createupdate_opportunity_trigger: execution of AfterInsert caused by: System.QueryException: List has no rows for assignment to SObject Trigger.createupdate_opportunity_trigger: line 7, column 1"

So, this means that OpportunityContactRole is not linked with Opportunity. Why this works if I use Classic? How do I get ContactId when using Lightning?
 
trigger createupdate_opportunity_trigger on Opportunity (after insert, after update) 
{
    for(Opportunity o:Trigger.new) 
    {
        if (o.id != null)
        {
            OpportunityContactRole contactRole = [select ContactId from OpportunityContactRole where IsPrimary = true and OpportunityId = :o.Id];
            if (contactRole != null)
            {
                System.debug('Found: ' + contactRole.ContactID);
            }
        }
    }
}

 
Hi,

  I have a below code which is working as expected it gives list of account names and contact name top to bottom

  Now my requirement is in contact we have NSE1 and NSE2 has two feilds  this needs to be added or sum and displayed when it is views from partner account
 
Example;  
        Account A is Top Parent  Has 1 Contacts  NSE1 = 1 and NSE2 = 1
        Account  B is Child of Account A Has 1 Contacts  NSE1= 1 and NSE2 = 1
        Account C is Child of Account B  Has 1 Contacts  NSE1= 0 and NSE2 = 1

If I see Account A Contact NSE1 and NSE2 should be NSE1 = 2 and NSE2 = 3
If I see Account A Contact NSE1 and NSE2 should be NSE1 = 1 and NSE2 = 2
If I see Account A Contact NSE1 and NSE2 should be NSE1 = 0 and NSE2 = 1

Code should display values as above. Please suggest me how to obtain this sum or add up the boolean values at parent level.
set<id> setactid = new set<id>();
    
Id accountId = '001W000000aDqeA';
        
 Account[] allparents = new Account[] {};
            
 Set<Id> parentIds = new Set<Id>{accountId};
                
 Account[] parent;
        
 do {
            
  parent = [select Id,ParentId, Name from Account where Id in :parentIds];
            
  allparents.addAll(parent);
            
  parentIds.clear();
            
  for (Account par : parent) 
                
  parentIds.add(par.ParentId);
            
  } while (parent.size() > 0);
        
  list<Account> Act = [select id, name from account where id in :allparents];
        
  for(Account A : Act){
     
    system.debug(a.name);  
     setactid.add(a.id);
           //dispaly here the sum of NSE1 and NSE2 account level grouping the contacts

      for(Contact C : [select id,name,NSE_1__c,NSE_2__c from contact where accountid in :setactid]){
        system.debug(c.name);
          system.debug('NSE_1__c   ' + c.NSE_1__c); //How to add this boolean values 
          system.debug('NSE_2__c   ' + c.NSE_2__c);
          
      }  
            
   }


Thanks
Sudhir