• Shri BE
  • NEWBIE
  • 55 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 2
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 11
    Replies
Hi Friends,

I have done trigger on Opportunity to insert Contact role when Opportunity is inserted based on accountId. I have a issue in Test Class where it covers only 23%. Kindly review and assist to complete the test class.
 
TestClass:

@isTest
public class updateContactRole_Test {
    static testMethod void createAccount()
    {    
        Account a = new Account();
        a.Name = 'Test Co.';
        a.BillingStreet = '298 S. Ringo Street';
        a.BillingCity = 'Little Rock';
        a.BillingState = 'AR';
        a.BillingPostalCode = '72201';
        a.BillingCountry = 'USA';
        a.Phone = '501-555-5555';
        a.Website = 'www.testco.com';
        insert a;
        System.debug('created account');
            
        //Then create a primary contact
        Contact c = new Contact();
        c.FirstName = 'Paul';
        c.LastName  = 'Test';
        c.AccountId = a.id;
        c.MailingStreet = '298 S. Ringo Street';
        c.MailingCity = 'Little Rock';
        c.MailingState = 'AR';
        c.MailingPostalCode = '72201'; 
        insert c;
        System.debug('created primary contact');
            
        //Now create an opportunity
        Opportunity o = new Opportunity();
        o.Name = 'New Record';
        o.StageName = 'Posted';
        o.CloseDate = Date.today();
        o.Description = 'Test Record';
        insert o;
        System.debug('created opportunity');
                  
        //Now update the OCR for the primary contact
        OpportunityContactRole ocr = new OpportunityContactRole();
        ocr.ContactId = c.Id;
        ocr.OpportunityId = o.Id;
        ocr.IsPrimary = TRUE;
        ocr.Role = 'Decision Maker';
        insert ocr;
        System.debug('created opportunity contact role for primary');          
        
    }
}
 
Trigger:

trigger updateContactRole on Opportunity (after insert, after update) {
    
    System.debug('-- Inside Opportunity Contact Role Trigger---');
    
    List<OpportunityContactRole> newContactRoleList = new List<OpportunityContactRole>();
    Set<Id> oppId = new Set<Id>();
    
    for(Opportunity o : [SELECT Id, AccountId FROM Opportunity WHERE AccountId IN: oppId]) {
       
/* Code not covering inside for loop */
 List <Contact> contacts = [SELECT Id FROM Contact WHERE accountId = : o.accountId];
        
        List <OpportunityContactRole> contactRoles = [SELECT Id, ContactId FROM OpportunityContactRole WHERE OpportunityId = :o.Id];
        
        if (contacts.size() > contactRoles.size()) {
            Set<Id> myContacts = new Set<Id>();
            for (OpportunityContactRole contactRole : contactRoles) {
                myContacts.add(contactRole.ContactId);
            }
            for (Contact contact : contacts) {
                if (!myContacts.contains(contact.Id)) {
                    OpportunityContactRole myContactRole = new OpportunityContactRole();
                    myContactRole.ContactId = contact.Id;
                    myContactRole.OpportunityId = o.Id;
                    newContactRoleList.add(myContactRole);
                    
                    // To prevent duplicate.
                    myContacts.add(contact.Id); 
                }
            }
        }
    }
    
    try {
        if(newContactRoleList.size()>0) {
            insert newContactRoleList;
        }
    }

    catch(Exception e) {
        System.debug(e);        
    }
}

Thanks in advance.
Hi Friends,

I am learning lightning and I have got stuck in creating lightning component. I have created a lightning datatable and I want to add viewall link after the table. If I click on the link it should navigate to next page contains all records.

Below is my component:
Apex Controller:

public class viewContactController {
    
    @AuraEnabled
    public static List<Contact> getContactRecords(String accountId)
    {        
        List<Contact> contactList = [SELECT Id, Name, Account.Name, Email, Phone, Title
                                       FROM Contact 
                                       WHERE Account.Id =: accountId ORDER BY LastModifiedDate Desc];
         
        if(contactList <> NULL && contactList.size() > 0)
            return contactList;
        else
            return NULL;
    }
}

Component:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" controller="viewContactController" access="global" >
    <aura:attribute name="contactList" type="List" description="contains Contact records"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/>	    
    
    <lightning:card iconName="standard:Daily_Practice__c" title="Related Contacts">
        <lightning:datatable data="{!v.contactList}"
                             columns="{!v.mycolumns}"
                             keyField="id"
                             hideCheckboxColumn="true"/>
    </lightning:card>
</aura:component>

Controller:

({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, helper);
    }
})

Controller Helper:

({
    fetchAccHelper : function(component, event, helper) {
        component.set('v.mycolumns', [                 
            	 {label: 'Action', fieldName: 'linkName', type: 'url', 
                		typeAttributes: {label: 'View Record',name: 'Name', target: '_blank'}},            	 
                 {label: 'Contact Name', fieldName: 'Name', type: 'text'},
            	 {label: 'Email', fieldName: 'Email', type: 'Email'},
            	 {label: 'Phone', fieldName: 'Phone', type: 'Phone'},
                 {label: 'Account Name', fieldName: 'accountId', type: 'text'}
        ]);
        
        var action = component.get("c.getContactRecords");
        action.setParams({
             "accountId":component.get("v.recordId")
        });
        
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var records =response.getReturnValue();
                records.forEach(function(record){
                    record.linkName = '/'+record.Id;
                    record.accountId = record.Account.Name
                });
                component.set("v.contactList", records);
            }
        });
        $A.enqueueAction(action);
    }
})
Below is sample viewall. I want to add same for my custom component.
User-added image

Thanks in advance.
Hi Friends,

I need help in completing below trigger.
I have a requirement, Two custom objects Obj A and Obj B which Obj A is Parent and Obj B is child. I am creating a child record based on daysbetween two dates Start Date and End Date in Parent object. This is working fine.
Now, If I edit the end date 
Eg: Start Date = 20/03/2020 and End Date = 22/03/2020. Daysbetween = 3. I will create 3 records in child Obj.
I am editing End Date = 25/03/2020.
Now Daysbetween = 6.
I want to create 3 more records. 
If I delete a date. Eg: End Date = 21/03/2020. Daysbetween = 2. I want to delete 1 record in child obj.
 
trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
        if(String.isNotBlank(sp.Phase_Start_Date__c) && String.isNotBlank(sp.Phase_End_Date__c) {

            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c);
            
            System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
            for(integer i=0; i<=daycount; i++)
            {
                Daily_Practice__c dps = new Daily_Practice__c();
                dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
                dps.StudyPlan__c = sp.Id;
                dps.Status__c = 'Assigned';
                dplist.add(dps);
            }    
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Let me know your suggestions to complete this requirement.

Thanks in advance.
Hi All,

I am getting system.null pointer exception: attempt to de-reference a null object, when trying to insert a record with null value in date field.
How to resolve this error. Need your assistance to fix this issue.

Below is my Trigger:
Trigger:


trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c); ----/// Getting error in this line.
            
System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
        for(integer i=0; i<=daycount; i++)
        {
            Daily_Practice__c dps = new Daily_Practice__c();
            dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
            dps.StudyPlan__c = sp.Id;
            dps.Status__c = 'Assigned';
            dplist.add(dps);
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Thanks
Hi everyone,

I am working on Apex bulk api request. I have completed class and got stuck in test class. I have started the test class and need to know how to complete and pass 75% code coverage.

Apex Class:
@RestResource(urlMapping='/insertAccount/*')
global with sharing class insertAccount
{
    @HttpPost
    global static List<Id> doPost(insertAccount.reqAcc reqAccount) 
    {
        Set<String> emails = new Set<String>();
        List<insertAccount.reqAccount> accounts = reqAccount.Account;
        
        for(insertAccount.reqAccount ac : accounts)
        {
            emails.add(ac.email);
            System.debug('--- Account Email ---' + ac.email);
            System.debug('--- Adding Account Email  ---' + emails);
        }

        Map<String, Id> mapAccount = new Map<String, Id>();
        
        for(Account a : [SELECT Id, PersonEmail FROM Account WHERE PersonEmail IN: emails])
        {
            mapAccount.put(a.PersonEmail, a.Id);
            System.debug('--- Map Acc Email ---' + a.PersonEmail);
        }
                
        List<Account> accList = new List<Account>();        
        
        for(insertAccount.reqAccount ac : accounts)
        {
            Account acc = new Account();
            if(mapAccount.containsKey(ac.email))
            {
                acc.Id = mapAccount.get(ac.email);
            }
            acc.lastname = ac.lastname;
            acc.firstname = ac.firstname;
            acc.PersonMobilePhone = ac.mobile;
            acc.PersonEmail = ac.email;
            acc.Billingcity = ac.city;
            acc.BillingState = ac.state;
            acc.BillingCountry = ac.country;
            acc.BillingPostalcode = ac.postal;
            acc.phone = ac.phone;
            
            accList.add(acc);
        }
        
        List<Id> successIds = new List<Id>();
        
        if(!accList.isEmpty())
        {
            for(Database.UpsertResult upsertresult: Database.upsert(accList))
            {
                successIds.add(upsertresult.getId());
            }
        }
        return successIds;
    }
    
    global class reqAcc 
    {
            global List<insertAccount.reqAccount> account;
    }
    
    global class reqAccount
    {
        Public String lastname;
        Public String firstname;
        Public String phone;
        Public String mobile;
        Public String email;
        Public String city;
        Public String state;
        Public String country;
        Public String postal;
    }
}
Test Class:
@IsTest
private class insertAccountTest
{
    static testMethod void testPostMethod()
    {
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/insertAccount';
        request.httpMethod = 'POST';
        RestContext.request = request;        
        
        String strId = insertAccount.doPost();
        System.assert(strId !=null );
    }
}
Thanks in Advance.

 
Hi All,
I need to update Account by comparing the email using Postman REST Api.
Below is my code which works fine but I have 1 issue. i.e.
It is updating all fields even though I update 1 or 2 fields from JSON response.

I update city but remaining all fields has become NULL after update.

Apex Class:
@RestResource(urlMapping='/insertAccount/*')
global with sharing class insertAccount
{
    //Update Method
    
    @HttpPut
    global static String fetchAccount(String name, String phone, String mobile, String email, String city, String state, String country, String postal)
    {
        RestRequest req = RestContext.request;
        RestResponse res = RestContext.response;        

        Account acc = new Account();
        
        //Query to get Matching Email from Account
        acc = [SELECT Id, Email__c FROM Account WHERE Email__c =:email];

        acc.Name = name;
        acc.MobilePhone__c = mobile;
        acc.Email__c = email;
        acc.Billingcity = city;
        acc.BillingState = state;
        acc.BillingCountry = country;
        acc.BillingPostalcode = postal;
        acc.phone = phone;
        update acc;

        return acc.Id;
    }
}
JSON Resonse:
{
    "name" : "Testing",
    "city" : "Dubai",
    "email" : "test@gmail.com"
}

Thanks.
 
Hi friends,

I am working on Rest API service and I got stuck in middle and need your help to complete the code.

I have a common field between account and order and based on that field I need to map account Id and insert order.

Kindly refer the below class and need how to get the account id.
 
@RestResource(urlMapping='/insertOrder/*')
global with sharing class insertOrder
{
    //Insert Method
    
    @HttpPost
    global static String doPost(String cusid, String pl, String res) 
    {
              
        Order ord = new Order();
       // Need to get the account id.
        ord.AccountId = acc.Id;       
       // Customer Id is the common field in both account and order.
        ord.Customer_ID__c = cusid;
        ord.PL__c = pl;
        ord.Res__c = res;
        
        insert ord;
        
        return ord.id;
    }
}

Thanks in Advance.
Hello Friends,

I got stuck in creating a Test Class. Getting error when saving the test class.
indly need your inputs to troubleshoot the error. Below is nmy Class and Test Class.
 
Class:::

public with sharing class victoriaBuildPDF {
    private final Order o;    
    
    public victoriaBuildPDF(ApexPages.StandardController standardPageController) {
        o = (Order)standardPageController.getRecord(); 
    }

    public PageReference savePdf() {
        PageReference pdf = Page.victoriaBuild;
        pdf.getParameters().put('id',o.id);
        Blob pdfBlob;

        if (!Test.isRunningTest()) {
            pdfBlob = pdf.getContent();
        } 
        else {
            pdfBlob = Blob.valueOf('PDF Test...');
        }
        
        Attachment attach = new Attachment(parentId = o.Id, Name = 'VictoriaBuild.pdf', body = pdfBlob, IsPrivate = false);
        insert attach;

        PageReference detailPage = new ApexPages.StandardController(o).view(); 
        detailPage.setRedirect(true);
        return detailPage;
        
    }
}
 
Test Class:::

@isTest
private class victoriaBuildPDF_Tests {
  private static testMethod void testSaveAndAttachPDF() {
    Account acc = new Account(Name = 'Test Account');
    insert acc;
  
    Order a = new Order(AccountId = acc.Id, EffectiveDate = system.today(), Status = 'Draft');
    insert a;

    ApexPages.currentPage().getParameters().put('Id', a.Id);
    
    victoriaBuildPDF con = new victoriaBuildPDF();
    con.savePDF();
  }
}
Error: Error: Compile Error: Constructor not defined: [victoriaBuildPDF].<Constructor>() at line 12 column 28

Thanks in Advance.
 
Hi Friends,

I had done with my scheduler and test class but I got stuck in code coverage issue and could not able to deploy into production.

Kindly need your help to complete the code.

Class :
global class orderItemsSchedulable Implements Schedulable {

    global void execute(SchedulableContext sc) {
        insertOrder();
    }

    public void insertOrder() {
    
        List<OrderItems__c> orderitemsList = new List<OrderItems__c>();
        
        orderitemsList = [SELECT Id, Name, Item_Id__c, Due_Date__c, Name__c, Discount_Amount__c, Price__c, Product_Id__c, Product_Type__c, Qty_Backordered__c, 
                                 Qty_Canceled__c, Qty_Invoiced__c, Qty_Ordered__c, Qty_Refunded__c, Qty_Returned__c, Qty_Shipped__c, Sku__c
                            FROM OrderItems__c WHERE CreatedDate = TODAY AND HOUR_IN_DAY(CreatedDate) > 1];
        
        System.debug('--- Order Items List Created ---' + orderitemsList.size());
        
        Set<String> orderIds = new Set<String>();
        List<Opportunitylineitem> oliinsertList = new List<Opportunitylineitem>();
        
        for(OrderItems__c oi : orderitemsList) {
            orderIds.add(oi.Name);
            orderIds.add(oi.Name__c);
            System.debug('--- OrderId Name: ---' + oi.Name);
            System.debug('--- OrderId Name: ---' + oi.Name__c);        
        }
        
        Map<String, List<Opportunitylineitem>> oliMap = new Map<String, List<Opportunitylineitem>>();
    
        Map<String, List<Opportunity>> oppMap = new Map<String, List<Opportunity>>();
        
        List<Opportunity> oppsList = new List<Opportunity>();
        oppsList = [SELECT Id, Name, (SELECT Id FROM Opportunitylineitems) FROM Opportunity WHERE Name IN: orderIds];
        
        if(!orderIds.isEmpty()) {
            for(Opportunity opps : oppsList) {
                if(!oppMap.containsKey(opps.Name)){
                    oppMap.put(opps.Name, new List<Opportunity> {opps});
                    System.debug('--- Inside OppMap ---' + oppMap);
                }
                else{
                    List<Opportunity> oppList = oppMap.get(opps.Name);
                    oppList.add(opps);
                    oppMap.put(opps.Name, oppList);
                    System.debug('--- Else oppMap ---' + oppList);
                }
            }
        }
        
        Pricebookentry pbe = [SELECT Id, Name, isActive FROM Pricebookentry WHERE isActive = true AND Name = 'Sample Product' Limit 1];
            
        for(OrderItems__c oi : orderitemsList) {
             if(oppMap.containsKey(oi.Name)) {
                for(Opportunity opp : oppMap.get(oi.Name)) {                    
                    if(opp.opportunitylineitems.size() == 0) {
                        Opportunitylineitem oli = new Opportunitylineitem ();
                        oli.OpportunityId = opp.Id;
                        oli.PricebookEntryId = pbe.Id;
                        oli.Quantity = 1;
                        oli.TotalPrice = oi.Price__c;
                        oli.item_id__c = oi.item_id__c;
                        oli.Name__c = oi.Name__c;
                        oli.product_id__c = oi.product_id__c;
                        oli.Due_Date__c = oi.Due_Date__c;
                        oli.product_type__c = oi.product_type__c;
                        oli.qty_backordered__c = oi.qty_backordered__c;
                        oli.qty_canceled__c = oi.qty_canceled__c;
                        oli.qty_invoiced__c = oi.qty_invoiced__c;
                        oli.qty_ordered__c = oi.qty_ordered__c;
                        oli.qty_refunded__c = oi.qty_refunded__c;
                        oli.qty_returned__c = oi.qty_returned__c;
                        oli.qty_shipped__c = oi.qty_shipped__c;
                        oli.Discount_Amount__c = oi.Discount_Amount__c;
                        oli.Sku__c = oi.Sku__c;
                        oliinsertList.add(oli);
                    }
                }
            }
        }
        
        if(oliinsertList.size() > 0) {
            insert oliinsertList;
        }
    }
}

test class :

@isTest(SeeAllData=true)
public class orderItemsSchedulableTest {
    
    Static testmethod void schedulerTest() {    
        
        String CRON_EXP = '0 05 * * * ?';
        
        Id RecordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
  
        Account acc = new Account(LastName = 'Test Account', recordtypeid = RecordTypeIdAccount);
        insert acc;
        
        Id pricebookId = Test.getStandardPricebookId();
            
        List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE PriceBook2.isStandard = true LIMIT 1];
                  
        //Create your product
        Product2 prod = new Product2(
             Name = 'Product X',
             ProductCode = 'Pro-X',
             isActive = true
        );
        insert prod;
        
        //Create your pricebook entry
        PricebookEntry pbEntry = new PricebookEntry(
             Pricebook2Id = pricebookId,
             Product2Id = prod.Id,
             UnitPrice = 100.00,
             IsActive = true
        );
        insert pbEntry;
        
        Opportunity opp = [SELECT Id, Name FROM Opportunity WHERE Name ='Sample']; 
            
        OpportunityLineItem oli = new OpportunityLineItem();                
        oli.OpportunityId = opp.Id;
        oli.PricebookEntryId = pbEntry.Id; 
        oli.Quantity = 1;
        oli.TotalPrice = 100;                
        oli.item_id__c = 123;
        oli.Name__c = 'Testing';
        oli.product_id__c = '1254';
        oli.Due_Date__c = System.today();
        oli.product_type__c = '32675';
        oli.qty_backordered__c = 0;
        oli.qty_canceled__c = 0;
        oli.qty_invoiced__c = 2;
        oli.qty_ordered__c = 1;
        oli.qty_refunded__c = 0;
        oli.qty_returned__c = 0;
        oli.qty_shipped__c = 2;
        oli.Sku__c = 'BUYCDF786';
        insert oli;
        
        Test.startTest();
            String jobId = system.schedule('ScheduleJobTest', CRON_EXP, new orderItemsSchedulable());
            CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id=: jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);                        
        Test.stopTest();
    }
}

Thanks.

 
Hi Experts,

I am getting the below error when I insert Opportunity Line Item in Test Class for trigger. Kindly help me how to rectify this error. Because of this my Code coverage is 70%.

first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: Quantity (Quantity mus be nonzero): [Quantity]

Your inputs are needed.

Thanks
Hi Friends,

My requirement is to compare 2 fields (one is Opportunity and other is Custom Object). Opportunity Field is Textfree and Custom Object field is Decimal. Objects doesnt have any master-detail or lookup relationship. Check the value in the field and compare the same value in custom object. If value is available then Insert the Opportunity Line Items where Opportunity Id should be the auto populated.
I am planning to go with Trigger on Custom Object. Kindly suggest how to start. 

Thanks.
Hi
My org is Non-Profit organization and we are looking for Salesforce Integration. We have a websiite and form for payment, after entering the card details and Pay selected it willl redirect to payment gateway wesite (Preferably SecurePay and multiple other payment gateways).. After Payment processed I need to create an Opportunity and attach the payment receipt to that opportunity. I want to know how can I do the integration. I check some apps in app exchange but they are all paid. Kindly suggest the way to achieve this process.

Thanks.
Hi Friends,

I am new to Integration concepts. I need help and assistance to learn integration concepts. I need to integrate a External System with Salesforce. 
1) When a order is created in the 3rd party Application, I need to create an opportunity. 
2) Third Party Application has Webhook which we can use with Salesforce. 

Please let me know how to approch this requirement and assistance in integrating the application.

Thanks.
Hi,

Written Trigger on Campaign Member and it is working fine as expected. I wrote a test class for the trigger and code coverage is 48%. Need assistance to complete the test class and deploy into production. Below is my Trigger and Test Class.
 
Trigger :

trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();    
    
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    }
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
            personAccountIds.add(acc.Id);
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    
    Set<Id> personAccountIds = new Set<Id>();
    List<Customer_Profile__c> existingCustomerProfiles = [SELECT id, business_accounts__c, person_accounts__c FROM Customer_Profile__c WHERE person_accounts__c IN :personAccountIds];
    
    Set<String> bizAcctCombo = new Set<String>();
    for(Customer_Profile__c cp : existingCustomerProfiles) {
        bizAcctCombo.add(String.valueOf(cp.business_accounts__c) + String.valueOf(cp.person_accounts__c));
    }
    
    List<CampaignMember> campaignMembers = [SELECT id, campaign.business_accounts__c, contactId FROM CampaignMember WHERE Id IN :Trigger.newMap.keyset()];
    
    for(CampaignMember cm : campaignMembers) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
                String bizAcctString = String.valueOf(cm.campaign.business_accounts__c) + String.valueOf(a.id);
                if (!bizAcctCombo.contains(bizAcctString)) {
                    Customer_Profile__c cusObj = new Customer_Profile__c();
                    cusObj.person_accounts__c = a.id;  
                    cusObj.Business_accounts__c = cm.campaign.business_accounts__c ;
                    customProfileList.add(cusObj);
                    bizAcctCombo.add(bizAcctString);
                }
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}
 
Test Class :

@isTest(SeeAllData = true)
private class insertCustomObjTest {
    private static testMethod void insertCustomObj() {
        system.debug('Started Member Insert Test Class');        
        Test.startTest();                    
            Account acct = new Account (Name = 'Test Account');
            insert acct;
            system.debug('Inserted Account, ID: ' + acct.id);
            
            Contact con = new Contact (FirstName = 'Sample', LastName = 'Contact', AccountId = acct.Id);
            insert con;
            system.debug('Inserted Contact, ID: ' + con.id);            

            Campaign camp = new Campaign (Name = 'Test', IsActive = TRUE);
            insert camp;
            system.debug('Inserted Campaign, ID: ' + camp.id);

            CampaignMember member = new CampaignMember (contactId = con.id, Status = 'sent', CampaignId = camp.Id);
            insert member;
            system.debug('Inserted CampaignMember, ID: ' + member.Id);
            system.debug('CampaignMember Status: ' + member.Status);
            system.debug('CampaignId Status: ' + member.CampaignId);
            system.debug('This should fire the Trigger');
            
            Customer_Profile__c testCusobj = new Customer_Profile__c (Name = 'Test Account');
            insert testCusobj;
            system.debug('Inserted Custom Object, ID: ' + testCusobj.id);
        Test.stopTest();
        
        List<Contact> ChgContact = [Select Id, Name FROM Contact WHERE Id = :con.Id];
        System.Debug (ChgContact[0].Id);
    }
}

Thanks in advance.
  • September 29, 2018
  • Like
  • 0
Hi Friends,

I need help in completing below trigger.
I have a requirement, Two custom objects Obj A and Obj B which Obj A is Parent and Obj B is child. I am creating a child record based on daysbetween two dates Start Date and End Date in Parent object. This is working fine.
Now, If I edit the end date 
Eg: Start Date = 20/03/2020 and End Date = 22/03/2020. Daysbetween = 3. I will create 3 records in child Obj.
I am editing End Date = 25/03/2020.
Now Daysbetween = 6.
I want to create 3 more records. 
If I delete a date. Eg: End Date = 21/03/2020. Daysbetween = 2. I want to delete 1 record in child obj.
 
trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
        if(String.isNotBlank(sp.Phase_Start_Date__c) && String.isNotBlank(sp.Phase_End_Date__c) {

            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c);
            
            System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
            for(integer i=0; i<=daycount; i++)
            {
                Daily_Practice__c dps = new Daily_Practice__c();
                dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
                dps.StudyPlan__c = sp.Id;
                dps.Status__c = 'Assigned';
                dplist.add(dps);
            }    
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Let me know your suggestions to complete this requirement.

Thanks in advance.
Hi All,

I am getting system.null pointer exception: attempt to de-reference a null object, when trying to insert a record with null value in date field.
How to resolve this error. Need your assistance to fix this issue.

Below is my Trigger:
Trigger:


trigger insertDailyPractices on Study_Plan__c (after insert) 
{
    System.debug('--- Inside Trigger ---');
    List<Daily_Practice__c> dplist = new List<Daily_Practice__c>();    
    
    for(Study_Plan__c sp : Trigger.New)
    {
            Integer daycount = sp.Phase_Start_Date__c.daysBetween(sp.Phase_End_Date__c); ----/// Getting error in this line.
            
System.debug('--- Inside For Loop ---' + sp.Phase_Start_Date__c);
            System.debug('--- Day Count ---' + daycount);
     
        for(integer i=0; i<=daycount; i++)
        {
            Daily_Practice__c dps = new Daily_Practice__c();
            dps.Due_Date__c = sp.Phase_Start_Date__c.addDays(i) + 1;
            dps.StudyPlan__c = sp.Id;
            dps.Status__c = 'Assigned';
            dplist.add(dps);
        }
    }
    
    if(dplist.size() > 0)
    {
        insert dplist;
    }    
    system.debug('--- Inserted Daily Practice ---'+ dplist.size());
}

Thanks
Hi everyone,

I am working on Apex bulk api request. I have completed class and got stuck in test class. I have started the test class and need to know how to complete and pass 75% code coverage.

Apex Class:
@RestResource(urlMapping='/insertAccount/*')
global with sharing class insertAccount
{
    @HttpPost
    global static List<Id> doPost(insertAccount.reqAcc reqAccount) 
    {
        Set<String> emails = new Set<String>();
        List<insertAccount.reqAccount> accounts = reqAccount.Account;
        
        for(insertAccount.reqAccount ac : accounts)
        {
            emails.add(ac.email);
            System.debug('--- Account Email ---' + ac.email);
            System.debug('--- Adding Account Email  ---' + emails);
        }

        Map<String, Id> mapAccount = new Map<String, Id>();
        
        for(Account a : [SELECT Id, PersonEmail FROM Account WHERE PersonEmail IN: emails])
        {
            mapAccount.put(a.PersonEmail, a.Id);
            System.debug('--- Map Acc Email ---' + a.PersonEmail);
        }
                
        List<Account> accList = new List<Account>();        
        
        for(insertAccount.reqAccount ac : accounts)
        {
            Account acc = new Account();
            if(mapAccount.containsKey(ac.email))
            {
                acc.Id = mapAccount.get(ac.email);
            }
            acc.lastname = ac.lastname;
            acc.firstname = ac.firstname;
            acc.PersonMobilePhone = ac.mobile;
            acc.PersonEmail = ac.email;
            acc.Billingcity = ac.city;
            acc.BillingState = ac.state;
            acc.BillingCountry = ac.country;
            acc.BillingPostalcode = ac.postal;
            acc.phone = ac.phone;
            
            accList.add(acc);
        }
        
        List<Id> successIds = new List<Id>();
        
        if(!accList.isEmpty())
        {
            for(Database.UpsertResult upsertresult: Database.upsert(accList))
            {
                successIds.add(upsertresult.getId());
            }
        }
        return successIds;
    }
    
    global class reqAcc 
    {
            global List<insertAccount.reqAccount> account;
    }
    
    global class reqAccount
    {
        Public String lastname;
        Public String firstname;
        Public String phone;
        Public String mobile;
        Public String email;
        Public String city;
        Public String state;
        Public String country;
        Public String postal;
    }
}
Test Class:
@IsTest
private class insertAccountTest
{
    static testMethod void testPostMethod()
    {
        RestRequest request = new RestRequest();
        request.requestUri ='/services/apexrest/insertAccount';
        request.httpMethod = 'POST';
        RestContext.request = request;        
        
        String strId = insertAccount.doPost();
        System.assert(strId !=null );
    }
}
Thanks in Advance.

 
Hi friends,

I am working on Rest API service and I got stuck in middle and need your help to complete the code.

I have a common field between account and order and based on that field I need to map account Id and insert order.

Kindly refer the below class and need how to get the account id.
 
@RestResource(urlMapping='/insertOrder/*')
global with sharing class insertOrder
{
    //Insert Method
    
    @HttpPost
    global static String doPost(String cusid, String pl, String res) 
    {
              
        Order ord = new Order();
       // Need to get the account id.
        ord.AccountId = acc.Id;       
       // Customer Id is the common field in both account and order.
        ord.Customer_ID__c = cusid;
        ord.PL__c = pl;
        ord.Res__c = res;
        
        insert ord;
        
        return ord.id;
    }
}

Thanks in Advance.
Hi Friends,

I had done with my scheduler and test class but I got stuck in code coverage issue and could not able to deploy into production.

Kindly need your help to complete the code.

Class :
global class orderItemsSchedulable Implements Schedulable {

    global void execute(SchedulableContext sc) {
        insertOrder();
    }

    public void insertOrder() {
    
        List<OrderItems__c> orderitemsList = new List<OrderItems__c>();
        
        orderitemsList = [SELECT Id, Name, Item_Id__c, Due_Date__c, Name__c, Discount_Amount__c, Price__c, Product_Id__c, Product_Type__c, Qty_Backordered__c, 
                                 Qty_Canceled__c, Qty_Invoiced__c, Qty_Ordered__c, Qty_Refunded__c, Qty_Returned__c, Qty_Shipped__c, Sku__c
                            FROM OrderItems__c WHERE CreatedDate = TODAY AND HOUR_IN_DAY(CreatedDate) > 1];
        
        System.debug('--- Order Items List Created ---' + orderitemsList.size());
        
        Set<String> orderIds = new Set<String>();
        List<Opportunitylineitem> oliinsertList = new List<Opportunitylineitem>();
        
        for(OrderItems__c oi : orderitemsList) {
            orderIds.add(oi.Name);
            orderIds.add(oi.Name__c);
            System.debug('--- OrderId Name: ---' + oi.Name);
            System.debug('--- OrderId Name: ---' + oi.Name__c);        
        }
        
        Map<String, List<Opportunitylineitem>> oliMap = new Map<String, List<Opportunitylineitem>>();
    
        Map<String, List<Opportunity>> oppMap = new Map<String, List<Opportunity>>();
        
        List<Opportunity> oppsList = new List<Opportunity>();
        oppsList = [SELECT Id, Name, (SELECT Id FROM Opportunitylineitems) FROM Opportunity WHERE Name IN: orderIds];
        
        if(!orderIds.isEmpty()) {
            for(Opportunity opps : oppsList) {
                if(!oppMap.containsKey(opps.Name)){
                    oppMap.put(opps.Name, new List<Opportunity> {opps});
                    System.debug('--- Inside OppMap ---' + oppMap);
                }
                else{
                    List<Opportunity> oppList = oppMap.get(opps.Name);
                    oppList.add(opps);
                    oppMap.put(opps.Name, oppList);
                    System.debug('--- Else oppMap ---' + oppList);
                }
            }
        }
        
        Pricebookentry pbe = [SELECT Id, Name, isActive FROM Pricebookentry WHERE isActive = true AND Name = 'Sample Product' Limit 1];
            
        for(OrderItems__c oi : orderitemsList) {
             if(oppMap.containsKey(oi.Name)) {
                for(Opportunity opp : oppMap.get(oi.Name)) {                    
                    if(opp.opportunitylineitems.size() == 0) {
                        Opportunitylineitem oli = new Opportunitylineitem ();
                        oli.OpportunityId = opp.Id;
                        oli.PricebookEntryId = pbe.Id;
                        oli.Quantity = 1;
                        oli.TotalPrice = oi.Price__c;
                        oli.item_id__c = oi.item_id__c;
                        oli.Name__c = oi.Name__c;
                        oli.product_id__c = oi.product_id__c;
                        oli.Due_Date__c = oi.Due_Date__c;
                        oli.product_type__c = oi.product_type__c;
                        oli.qty_backordered__c = oi.qty_backordered__c;
                        oli.qty_canceled__c = oi.qty_canceled__c;
                        oli.qty_invoiced__c = oi.qty_invoiced__c;
                        oli.qty_ordered__c = oi.qty_ordered__c;
                        oli.qty_refunded__c = oi.qty_refunded__c;
                        oli.qty_returned__c = oi.qty_returned__c;
                        oli.qty_shipped__c = oi.qty_shipped__c;
                        oli.Discount_Amount__c = oi.Discount_Amount__c;
                        oli.Sku__c = oi.Sku__c;
                        oliinsertList.add(oli);
                    }
                }
            }
        }
        
        if(oliinsertList.size() > 0) {
            insert oliinsertList;
        }
    }
}

test class :

@isTest(SeeAllData=true)
public class orderItemsSchedulableTest {
    
    Static testmethod void schedulerTest() {    
        
        String CRON_EXP = '0 05 * * * ?';
        
        Id RecordTypeIdAccount = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Person Account').getRecordTypeId();
  
        Account acc = new Account(LastName = 'Test Account', recordtypeid = RecordTypeIdAccount);
        insert acc;
        
        Id pricebookId = Test.getStandardPricebookId();
            
        List<PriceBookEntry> priceBookList = [SELECT Id, Product2Id, Product2.Id, Product2.Name FROM PriceBookEntry WHERE PriceBook2.isStandard = true LIMIT 1];
                  
        //Create your product
        Product2 prod = new Product2(
             Name = 'Product X',
             ProductCode = 'Pro-X',
             isActive = true
        );
        insert prod;
        
        //Create your pricebook entry
        PricebookEntry pbEntry = new PricebookEntry(
             Pricebook2Id = pricebookId,
             Product2Id = prod.Id,
             UnitPrice = 100.00,
             IsActive = true
        );
        insert pbEntry;
        
        Opportunity opp = [SELECT Id, Name FROM Opportunity WHERE Name ='Sample']; 
            
        OpportunityLineItem oli = new OpportunityLineItem();                
        oli.OpportunityId = opp.Id;
        oli.PricebookEntryId = pbEntry.Id; 
        oli.Quantity = 1;
        oli.TotalPrice = 100;                
        oli.item_id__c = 123;
        oli.Name__c = 'Testing';
        oli.product_id__c = '1254';
        oli.Due_Date__c = System.today();
        oli.product_type__c = '32675';
        oli.qty_backordered__c = 0;
        oli.qty_canceled__c = 0;
        oli.qty_invoiced__c = 2;
        oli.qty_ordered__c = 1;
        oli.qty_refunded__c = 0;
        oli.qty_returned__c = 0;
        oli.qty_shipped__c = 2;
        oli.Sku__c = 'BUYCDF786';
        insert oli;
        
        Test.startTest();
            String jobId = system.schedule('ScheduleJobTest', CRON_EXP, new orderItemsSchedulable());
            CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id=: jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);                        
        Test.stopTest();
    }
}

Thanks.

 
Hi Experts,

I am getting the below error when I insert Opportunity Line Item in Test Class for trigger. Kindly help me how to rectify this error. Because of this my Code coverage is 70%.

first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: Quantity (Quantity mus be nonzero): [Quantity]

Your inputs are needed.

Thanks
Hi Friends,

My requirement is to compare 2 fields (one is Opportunity and other is Custom Object). Opportunity Field is Textfree and Custom Object field is Decimal. Objects doesnt have any master-detail or lookup relationship. Check the value in the field and compare the same value in custom object. If value is available then Insert the Opportunity Line Items where Opportunity Id should be the auto populated.
I am planning to go with Trigger on Custom Object. Kindly suggest how to start. 

Thanks.
Hi
My org is Non-Profit organization and we are looking for Salesforce Integration. We have a websiite and form for payment, after entering the card details and Pay selected it willl redirect to payment gateway wesite (Preferably SecurePay and multiple other payment gateways).. After Payment processed I need to create an Opportunity and attach the payment receipt to that opportunity. I want to know how can I do the integration. I check some apps in app exchange but they are all paid. Kindly suggest the way to achieve this process.

Thanks.
Hi,

Written Trigger on Campaign Member and it is working fine as expected. I wrote a test class for the trigger and code coverage is 48%. Need assistance to complete the test class and deploy into production. Below is my Trigger and Test Class.
 
Trigger :

trigger insertCustomObj on CampaignMember (after insert, after update) {

    System.debug('---- Entered Trigger ----'); 
    
    List<Customer_Profile__c> customProfileList = new List<Customer_Profile__c>();    
    Set<Id> accountIds = new Set<Id>();    
    
    for(CampaignMember cm : Trigger.new) {
        System.debug('---- Inside CampaignMember : ----');
        accountIds.add(cm.contactId);
    }
    
    Map<Id, List<Account>> accMap = new Map<Id, List<Account>>();
    
    if(!accountIds.isEmpty()){
        System.debug('---- Checking Account Id : ----');
        for(Account acc: [SELECT id, name, personcontactId FROM Account WHERE personcontactId IN:accountIds]){
            personAccountIds.add(acc.Id);
            if(!accMap.containsKey(acc.personcontactId)){
                accMap.put(acc.personcontactId, new List<Account>{acc});
            }
            else{
                List<Account> accList = accMap.get(acc.personcontactId);
                accList.add(acc);
                accMap.put(acc.personcontactId, accList);
            }
        }
    }            
    
    Set<Id> personAccountIds = new Set<Id>();
    List<Customer_Profile__c> existingCustomerProfiles = [SELECT id, business_accounts__c, person_accounts__c FROM Customer_Profile__c WHERE person_accounts__c IN :personAccountIds];
    
    Set<String> bizAcctCombo = new Set<String>();
    for(Customer_Profile__c cp : existingCustomerProfiles) {
        bizAcctCombo.add(String.valueOf(cp.business_accounts__c) + String.valueOf(cp.person_accounts__c));
    }
    
    List<CampaignMember> campaignMembers = [SELECT id, campaign.business_accounts__c, contactId FROM CampaignMember WHERE Id IN :Trigger.newMap.keyset()];
    
    for(CampaignMember cm : campaignMembers) {
        if(accMap.containsKey(cm.contactId)){
            for(Account a: accMap.get(cm.contactId)){
                String bizAcctString = String.valueOf(cm.campaign.business_accounts__c) + String.valueOf(a.id);
                if (!bizAcctCombo.contains(bizAcctString)) {
                    Customer_Profile__c cusObj = new Customer_Profile__c();
                    cusObj.person_accounts__c = a.id;  
                    cusObj.Business_accounts__c = cm.campaign.business_accounts__c ;
                    customProfileList.add(cusObj);
                    bizAcctCombo.add(bizAcctString);
                }
            }
        }
        System.debug('--- Customer Profile List ---' + customProfileList.size());
    }
    try{
        if(customProfileList.size()>0) {
            System.debug('--- Inside CustomObj ---');
            insert customProfileList;
        }
        System.debug('--- Total Custom Object Inserted---'); 
    }
    
    catch (Exception e){
        System.debug('The following exception has occurred: ' + e.getLineNumber() + ' : '  + e.getMessage());
    }    
}
 
Test Class :

@isTest(SeeAllData = true)
private class insertCustomObjTest {
    private static testMethod void insertCustomObj() {
        system.debug('Started Member Insert Test Class');        
        Test.startTest();                    
            Account acct = new Account (Name = 'Test Account');
            insert acct;
            system.debug('Inserted Account, ID: ' + acct.id);
            
            Contact con = new Contact (FirstName = 'Sample', LastName = 'Contact', AccountId = acct.Id);
            insert con;
            system.debug('Inserted Contact, ID: ' + con.id);            

            Campaign camp = new Campaign (Name = 'Test', IsActive = TRUE);
            insert camp;
            system.debug('Inserted Campaign, ID: ' + camp.id);

            CampaignMember member = new CampaignMember (contactId = con.id, Status = 'sent', CampaignId = camp.Id);
            insert member;
            system.debug('Inserted CampaignMember, ID: ' + member.Id);
            system.debug('CampaignMember Status: ' + member.Status);
            system.debug('CampaignId Status: ' + member.CampaignId);
            system.debug('This should fire the Trigger');
            
            Customer_Profile__c testCusobj = new Customer_Profile__c (Name = 'Test Account');
            insert testCusobj;
            system.debug('Inserted Custom Object, ID: ' + testCusobj.id);
        Test.stopTest();
        
        List<Contact> ChgContact = [Select Id, Name FROM Contact WHERE Id = :con.Id];
        System.Debug (ChgContact[0].Id);
    }
}

Thanks in advance.
  • September 29, 2018
  • Like
  • 0