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

  • Chatter
    Feed
  • 975
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 8268
    Replies

Hi!

Have tried to get this to work for many hours now, but can't find a solution. I have written a cusom controller for a visualforce page that looks like the one below. And get 0% code coverage on the Apex Class.

Any idea what's wrong?

Controller:

public class outboundLeadStart {
    // ApexPages.StandardSetController must be instantiated
    // for standard list controllers
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT Id, Name, Company, Country, CreatedDate, Status FROM Lead WHERE Status='New' AND OwnerId= :UserInfo.getUserID() ORDER BY CreatedDate DESC LIMIT 100]));
            }
            setCon.setPageSize(setCon.getResultSize());
            return setCon;
        }
        set;
    }
    
    public integer getCountLeads() {
            String statusStage = 'New';
            String ownerId = UserInfo.getUserID();
            return(Database.countQuery('SELECT count() FROM Lead WHERE Status= :statusStage AND OwnerId= :ownerId')); // Returns Integer        
    }
    
    // Initialize setCon and return a list of records
    public List<Lead> getLeads() {
        return (List<Lead>) setCon.getRecords();
    }
    
    public PageReference save() {
        
        try {
            update setCon.getRecords();
        } catch(DMLException e) {
            Apexpages.addmessages(e);
        }
        
        PageReference pageRef = new PageReference('/lightning/n/Outbound_Planning');
        pageRef.setRedirect(true);
        return pageRef;        
    }    
}

And the test class looks like this:
@isTest
private class testoutboundLeadStartTest {
    static testMethod void testoutboundLeadStartTest() 
    {
        User u = new User(
            ProfileId = [SELECT Id FROM Profile WHERE Name = 'Sales Representative'].Id,
            LastName = 'last',
            Email = 'last@example.com',
            Username = 'last@example.com' + System.currentTimeMillis(),
            CompanyName = 'TEST',
            Title = 'title',
            Alias = 'alias',
            TimeZoneSidKey = 'America/Los_Angeles',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US'
        );
        
        insert u;
        
        Id theOwnerId = UserInfo.getUserID();
        
        ApexPages.StandardSetController setCon;
        PageReference pageRef = Page.outboundLeadsStart;
        
        List <Lead> addedLeads = new List<Lead>();
        
        Lead testLead = new Lead();
        testLead.LastName='Test Lead';
        testLead.Company='Test Company1';
        testLead.Status='New';
        testLead.OwnerId=theOwnerId;
        insert testLead;
        
        List<Lead> cus = new List<Lead>{};
            
        Test.startTest();
        System.assertEquals('Test Lead', testLead.LastName);
        Test.setCurrentPage(pageRef);
        outboundLeadStart controller = new outboundLeadStart();
        Test.stopTest();
        
    }        
}
 

Can't understand why this get 0% code coverage on the Apex Class.

BR,
Andreas


 
An <a> tag in the html file of the lwc is only adding the desired url to the current url of the community page that the lwc is in.
Hi have a lightning component datatable that is populated by a query with a subquery in it. I need the second column to be poulated with a value from the subquery but I can't seem to figure out how to set the field name for the the subquery field. 

Screen shot: (RPF Con should map to sub query field.
User-added imageApex Class
public class RFPOppListController {

        @AuraEnabled
    public static List <Opportunity> fetchOpps (String oppId) {
        //Qyery 10 
        List<Opportunity> oppList = [SELECT Opportunity.Name, (select Contact__r.Name from Opportunity_Contact_Roles__r where Contact_roles__c = 'RFP consultant') FROM Opportunity];
        //return lis
        return oppList;
    }
}

Component:
<aura:component controller="RFPOppListController" access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId">

    <aura:attribute type="Opportunity[]" name="oppList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="updatedRecord" type="Object[]" />


     
    <aura:handler name="init" value="{!this}" action="{!c.fetchOPPS}"/>
     
    <lightning:datatable aura:id="oppsDataTable"
                         data="{! v.oppList }"
                         columns="{! v.mycolumns }"
                         keyField="Id"
                         hideCheckboxColumn="true"
                         onsave ="{!c.onSave}"
                         />
     
</aura:component>

Controller
({
    fetchOPPS : function(component, event, helper) {
        helper.fetchOPPSHelper(component, event, helper);    

    }
})
Helper
({
    fetchOPPSHelper : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Opp Name', fieldName: 'Name', editable:'true', sortable:'true', type: 'text'},          
            {label: 'RFP Con', fieldName: 'Opportunity_Contact_Roles__r.Contact__r.Name', editable:'true', sortable:'true', type: 'date'}   
            ]);
        debugger;
        var action = component.get("c.fetchOpps");      
        var operID = component.get("v.recordId");
        console.log("operID" + operID);
        action.setParams({
            oppId:operID
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.oppList", response.getReturnValue());
            }
        }); 
        $A.enqueueAction(action);
    }
})


BTW, here is a debugger screenshot of of the value I am trying to display:
User-added image
Article version is being maintained in salesforce classic upto 30 but the same is not being done in lightning.  I need help , why version is not maintain in lightning.
This is Apex Class
public with sharing class costsheet {
 
 public costsheet(ApexPages.StandardController controller) {

    }

 public List<Order> ordwrap = new List<Order>();
 public List<Opportunity> oppwrap = new List<Opportunity>();
 
 
 
 public costsheet()
 {
  this.SOWrappers = new List<SOWrapper>();
  ordwrap=[Select id,Cost_Price_As_per_Allocation__r.CI__c from Order];
  oppwrap=[select Id,name,Account.Name from opportunity];
  for(opportunity opp:oppwrap){
                for(Order ord: ordwrap){
                    If(opp.id == ord.id)
                    {
                        SOWrapper wrapper = new SOWrapper(opp, ord);
                        this.SOWrappers.add(wrapper);
                    }
                        
                    }
                }
 }
 public List<SOWrapper> SOWrappers{get;set;}
 public class SOWrapper{
        public Order order{get;set;}
        public Opportunity opportunity{get;set;}
        public Cost_Price__c costprice{get;set;}
        
        public SOWrapper(Order ord, Opportunity opp,Cost_Price__c cp){
            order= ord;
            opportunity = opp;
            costprice = cp;
        }
    }
    
}
Help me. What's wrong with the code? I'm trying to get All the Fields of Object.
@AuraEnabled
    public static List<SelectOption> getAllObjectFields(String objectName) {
        List<SelectOption> fieldList = new List<SelectOption>();
        Map <String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.values()) {
            if (sfield.getDescribe().isAccessible()) {
                fieldList .add(new SelectOption(sfield.getDescribe().getName(),sfield.getDescribe().getLabel()));
            }
        }
        return fieldList ;
    }

 
I followed the tutorial here (https://trailhead.salesforce.com/content/learn/modules/api_basics/api_basics_bulk?trail_id=force_com_dev_intermediate) but couldnt pass because I can only inject 100 users a time. I checked the failedResult User-added image
looks like it use SOQL for each individual record, I must did something wrong?
"Your Apex code contains field level access checks that are redundant now that you've added 'WITH SECURITY_ENFORCED'. Please check your code again."

Code is:-

@RestResource(urlMapping='/secureApexRest')
global with sharing class SecureApexRest {
    @HttpGet
    global static Contact doGet(){
        Id recordId = RestContext.request.params.get('id');
        Contact result;
        if (recordId == null){
            throw new FunctionalException('Id parameter is required');
        }
        if (Schema.SObjectType.Contact.isAccessible()
            && Schema.SObjectType.Contact.fields.Name.isAccessible()
            && Schema.SObjectType.Contact.fields.Secret_Key__c.isAccessible()){
            List<Contact> results = [SELECT id FROM Contact WHERE Id = :recordId WITH SECURITY_ENFORCED];
            if (!results.isEmpty()) {
                result = results[0];
            }
        } else{
            throw new SecurityException('You don\'t have access to all contact fields required to use this API');
        }
        return result;
    }
    public class FunctionalException extends Exception{}
    public class SecurityException extends Exception{}
}

Kindly suggest me what exactly I need to change in the code.
Thanks inadvance.
Please help me to display more than 1000 lines in a visualforce page.
public class InventoryCentralOficce {

      public List<AggregateResult> allproduct{get;set;}

     public InventoryCentralOficce() {

   allproduct = [
      
  SELECT Product_Hiden_Name__c, UM__c ,SUM(On_Hand__c)onHand,  SUM(Pending__c)pending,  SUM(Available__c)avail 
      FROM Articles_Containers__c 
      WHERE IsOpened__c = 1 AND FFP_Centers__c = 'Central Office'
GROUP BY Product_Hiden_Name__c , UM__c 
HAVING SUM(On_Hand__c) >0 
ORDER BY Product_Hiden_Name__c, UM__c limit 50000];
      
      

      }
}

 
I covered 40% with the below test class. Help me to cover 75%.
Apex Class:
public class FFQExt 
{
Public attachment objAttachment
{
get
{
if (objAttachment == null)
objAttachment = new Attachment();
return objAttachment ;
}
set;
}
public Id recordId {get; set;}
Public FFQ__C l{get; set;}
public String currentRecordId {get;set;}
public FFQExt(ApexPages.StandardController stdCon) 
{
currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
this.recordId = stdCon.getId();
this.l = (FFQ__c)stdCon.getRecord();  
objAttachment = new Attachment();
l = new FFQ__c();
l = [select Name, id, Business_Address__c, Business_Phone_Number__c, City__c, Client__c, Corporate_Structure__c, County__c, CPA_Contact__c, CPA_Contact_Email__c, 
CPA_Contact_Name__c, CPA_Contact_Phone__c, Do_you_ever_rehire_employees__c, MultipleEIN__c, Do_you_have_plans_for_Future_Expansion__c, Do_you_have_Recent_Expansion__c,
EIN__c, Estimated_Date_of_Tax_Filing__c, estimated_number_of_employees_hired_per__c, Executive_Contact__c, Executive_Contact_Email__c, Executive_Contact_Name__c,
Executive_Contact_Phone__c, Federal_Empowerment_Zone_Wage_Credit__c, First_Name__c, First_NameofPerson__c, Fiscal_Year_End_Date__c, General_Tax_Status__c, 
How_many_current_employees_do_you_have__c, How_many_W2s_were_distributed_last_year__c, HR_Contact__c, HR_Contact_Email__c, HR_Contact_Name__c, HR_Contact_Phone__c,
HR_Platform_to_onboard_your_Employees__c, Indian_Employment_Tax_Credit__c, Invoice_Contact__c, Invoice_Contact_Email__c, Invoice_Contact_Name__c, Invoice_Contact_Phone__c,
Legal__c, Is_your_business_Seasonal__c, I_understand__c, Last_Name__c, Last_NameofPerson__c, Legal_Address__c, Legal_City__c, Legal_County__c, Legal_Entity_Name__c, Legal_State__c,
Legal_Zip__c, list_all_locations_worksites__c, Payroll_Contact__c, Payroll_Contact_Email__c, Payroll_Contact_Name__c, Payroll_Contact_Phone__c, Please_list_all_EIN_Legal_Entities_below__c, 
Primary_Contact_Email__c, Primary_Contact_Number__c, Primary_Contact_Title__c, State__c, States_State_IDs_with_Tax_Liability__c, State_Specific_Incentives__c, To_begin_participation__c,
Which_HR_Platform_are_you_utilizing__c, Which_Payroll_Provider_are_you_using__c, WOTC__c, Zip__c from FFQ__c where id =: currentRecordId ];

}
Public void dosave()
{
if(objAttachment.body == null) 
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please upload your Documents'));
return ApexPages.CurrentPage();
}
else
{
upsert l;
objAttachment.ParentId = l.id;
try 
{
upsert objAttachment;
}
catch (DMLException e) 
{
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error Submitting Form'));
return null;
}
finally
{
objAttachment.body = null; // clears the viewstate
objAttachment = new Attachment();
}
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Form Submitted Successfully'));
 PageReference mypage = new PageReference('/apex/thankyou');
   mypage.setRedirect(true);
   return mypage;
return null;
}
}
}
Test Class:
 
@isTest
private class FFQExt_Test1{
  @testSetup
  static void setupTestData(){
    test.startTest();
    FFQ__c ffq_Obj = new FFQ__c(Name = 'Name714', First_Name__c = 'First917', Last_Name__c = 'Last_775', Primary_Contact_Title__c = 'Prima305', Primary_Contact_Email__c = 'Email16@test.com', Primary_Contact_Number__c = '54343-6724', Business_Address__c = '18', City__c = 'City__c632', State__c = 'Alabama', Zip__c = 'Zip__c497', Business_Phone_Number__c = '54343-92658', Legal_Entity_Name__c = 'Legal220', Legal__c = false, EIN__c = 25, MultipleEIN__c = false, Please_list_all_EIN_Legal_Entities_below__c = '27', list_all_locations_worksites__c = '28', Corporate_Structure__c = 'C-Corp', Estimated_Date_of_Tax_Filing__c = Date.today(), General_Tax_Status__c = 'Paying Regular Tax', Fiscal_Year_End_Date__c = Date.today(), States_State_IDs_with_Tax_Liability__c = '33', Do_you_have_Recent_Expansion__c = false, Do_you_have_plans_for_Future_Expansion__c = false, Executive_Contact_Name__c = 'Execu607', Executive_Contact_Email__c = 'Email37@test.com', Executive_Contact_Phone__c = '54343-11689', CPA_Contact_Name__c = 'CPA_C106', CPA_Contact_Phone__c = '54343-93693', CPA_Contact_Email__c = 'Email41@test.com', HR_Contact_Name__c = 'HR_Co140', HR_Contact_Email__c = 'Email43@test.com', HR_Contact_Phone__c = '54343-70632', Invoice_Contact_Name__c = 'Invoi739', Invoice_Contact_Email__c = 'Email46@test.com', Invoice_Contact_Phone__c = '54343-50578', Payroll_Contact_Name__c = 'Payro557', Payroll_Contact_Email__c = 'Email49@test.com', Payroll_Contact_Phone__c = '54343-67706', HR_Platform_to_onboard_your_Employees__c = 'Yes', Which_HR_Platform_are_you_utilizing__c = 'Which567', Which_Payroll_Provider_are_you_using__c = 'Which997', How_many_current_employees_do_you_have__c = 54, How_many_W2s_were_distributed_last_year__c = 55, estimated_number_of_employees_hired_per__c = 'estim415', Is_your_business_Seasonal__c = 'Is_yo660', Do_you_ever_rehire_employees__c = 'Do_yo497', First_NameofPerson__c = 'First430', Last_NameofPerson__c = 'Last_585', Legal_Address__c = '61', Legal_City__c = 'Legal521', Legal_Zip__c = 63, Legal_State__c = 'Alabama', WOTC__c = false, State_Specific_Incentives__c = false, Federal_Empowerment_Zone_Wage_Credit__c = false, Indian_Employment_Tax_Credit__c = false, Executive_Contact__c = false, CPA_Contact__c = false, HR_Contact__c = false, Invoice_Contact__c = false, Payroll_Contact__c = false, To_begin_participation__c = '74', County__c = 'Count208', Legal_County__c = 'Legal590', I_understand__c = 'Yes');
    Insert ffq_Obj; 
    test.stopTest();
  }
  static testMethod void test_dosave_UseCase1(){
    List<FFQ__c> ffq_Obj  =  [SELECT Id,Name,First_Name__c,Last_Name__c,Primary_Contact_Title__c,Primary_Contact_Email__c,Primary_Contact_Number__c,Business_Address__c,City__c,State__c,Zip__c,Business_Phone_Number__c,Legal_Entity_Name__c,Legal__c,EIN__c,MultipleEIN__c,Please_list_all_EIN_Legal_Entities_below__c,list_all_locations_worksites__c,Corporate_Structure__c,Estimated_Date_of_Tax_Filing__c,General_Tax_Status__c,Fiscal_Year_End_Date__c,States_State_IDs_with_Tax_Liability__c,Do_you_have_Recent_Expansion__c,Do_you_have_plans_for_Future_Expansion__c,Executive_Contact_Name__c,Executive_Contact_Email__c,Executive_Contact_Phone__c,CPA_Contact_Name__c,CPA_Contact_Phone__c,CPA_Contact_Email__c,HR_Contact_Name__c,HR_Contact_Email__c,HR_Contact_Phone__c,Invoice_Contact_Name__c,Invoice_Contact_Email__c,Invoice_Contact_Phone__c,Payroll_Contact_Name__c,Payroll_Contact_Email__c,Payroll_Contact_Phone__c,HR_Platform_to_onboard_your_Employees__c,Which_HR_Platform_are_you_utilizing__c,Which_Payroll_Provider_are_you_using__c,How_many_current_employees_do_you_have__c,How_many_W2s_were_distributed_last_year__c,estimated_number_of_employees_hired_per__c,Is_your_business_Seasonal__c,Do_you_ever_rehire_employees__c,First_NameofPerson__c,Last_NameofPerson__c,Legal_Address__c,Legal_City__c,Legal_Zip__c,Legal_State__c,WOTC__c,State_Specific_Incentives__c,Federal_Empowerment_Zone_Wage_Credit__c,Indian_Employment_Tax_Credit__c,Executive_Contact__c,CPA_Contact__c,HR_Contact__c,Invoice_Contact__c,Payroll_Contact__c,To_begin_participation__c,County__c,Legal_County__c,I_understand__c from FFQ__c];
    System.assertEquals(true,ffq_Obj.size()>0);
    PageReference pageRef = Page.FFQ;
    pageRef.getParameters().put('id','test');
    Test.setCurrentPage(pageRef);
    FFQExt obj01 = new FFQExt(new ApexPages.StandardController(ffq_Obj[0]));
    obj01.objAttachment = new attachment();
    obj01.recordId = '01p90000006uk2w';
    obj01.l = ffq_Obj[0];
    obj01.currentRecordId = 'test data';
    obj01.dosave();
  }
}


 

I am getting this error on line 0 in my apex code. This is for spring '19 PD1 maintenance

@RestResource(urlMapping='/secureApexRest')
global with sharing class SecureApexRest {
    @HttpGet
    global static Contact doGet(){
        Id recordId = RestContext.request.params.get('id');
        Contact result;
        if (recordId == null){
            throw new FunctionalException('Id parameter is required');
        }
        List<Contact> results;
        try{
            results = [SELECT id, Name, Secret_Key__c FROM Contact WHERE id=:recordId WITH SECURITY_ENFORCED];
        }catch(QueryException e){}
        
        if (!results.isEmpty()) {
            result = results[0];
        }
        return result;
    }
    public class FunctionalException extends Exception{}
    public class SecurityException extends Exception{}
}

Hi, I am getting an error while completing a challenge.
"
The Opportunity Amount field does not appear to be tracking field value changes."

I am struggling to find this change. Please help. Thanks
 
Hi guys,

I'm relatively new to Apex and am struggling a bit with a Test Class - I hope you can help!

Here is my Apex Trigger to create new Community users when Contacts are inserted:
 
trigger NewCommUser on Contact (After insert) {
     
     if(Trigger.isInsert){ 
     
         for(Contact co : trigger.new){
            Contact con = [select id,email,firstName,lastname,accountId,Do_Not_Grant_Community_Access__c,Account_Status_Text__c from Contact where Id =:co.Id];         
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.EmailHeader.triggerUserEmail = false;       
            dmo.EmailHeader.triggerOtherEmail = false;
            dmo.EmailHeader.triggerAutoResponseEmail = false;       
            dmo.optAllOrNone = false;

            // Create Community Hub user
            List<User> unames = [select username from user where email =:con.email LIMIT 1];
            List<Contact> accountstatus = [select id from contact where Account_Status_Text__c = 'Signed-Up' and Id=:co.Id LIMIT 1];
            
            string userAlias;
            if (con.firstName.length() > 8)
            userAlias = con.firstName.substring(0,8); else userAlias = con.firstName;    
            
            if(unames.isEmpty() && !con.Do_Not_Grant_Community_Access__c && accountstatus.Size()>0){
                string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):''; 
                nick += Datetime.now().getTime();
                User newUser1 = new User(alias=userAlias, email = con.email, emailencodingkey = 'UTF-8', firstname = con.firstName, lastname = con.lastname, languagelocalekey = 'en_US',localesidkey = 'en_GB',contactId = con.Id,timezonesidkey = 'Europe/London',username = con.email,CommunityNickname = nick,ProfileId ='00e58000000NkUd', IsActive = true);
                newUser1.setOptions(dmo); insert newUser1;
            }
         }
     }
}

And here is my Test Class:
 
@isTest
public class NewCommUserTest {
    
    @Testsetup
    static void dataSetup() {
        
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator']; 
    String orgId = UserInfo.getOrganizationId();
    String dateString = String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
    Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
    String uniqueName = orgId + dateString + randomInt;
        
        
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
                          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
                          LocaleSidKey='en_US', ProfileId = p.Id, 
                          TimeZoneSidKey='America/Los_Angeles', UserName=uniqueName + '@test' + orgId + '.org');
        
        u.UserRoleId=[select Id from UserRole where Name='CEO'].Id;
        
        //System.debug([select Id from UserRole where Name='CEO']);
        insert u;
       
        System.runAs(u) {
            Account a = new Account();
            a.Name = 'Test Account';
            insert a;                 
            
            Contact c = new Contact();
            c.LastName = ' Contact1';
            c.FirstName = 'test';
            
            c.Account_Status_Text__c = 'Signed-Up';
            c.Email = 'standarduser1@testorg.com';
            c.Do_Not_Grant_Community_Access__c = true;
            c.AccountId = a.Id;
            insert c;
            
            c.Do_Not_Grant_Community_Access__c = FALSE;
            update c;
        }
        
        
    }    
    
    @isTest static void testUpdateOrgForNewBusiness2() { 
        
        Account a = [select Id from Account limit 1];
        Contact c = new Contact();
        c.LastName = 'Contact1234';
        c.FirstName = 'test';
        
        c.Account_Status_Text__c = 'Signed-Up';
        c.Email = 'standarduser1@testorg.com';
        c.Do_Not_Grant_Community_Access__c = true;
        c.Account = a;
        insert c;
        
        c.Do_Not_Grant_Community_Access__c = FALSE;
        c.LastName = 'Contact1';
        update c;
        
    }
    
}

I'm currently at 73% coverage but so far am having trouble with this part of my Trigger:
 
string nick = con.email!=null?con.email.substring(0, con.email.indexOf('@')):''; 
nick += Datetime.now().getTime();
User newUser1 = new User(alias=userAlias, email = con.email, emailencodingkey = 'UTF-8', firstname = con.firstName, lastname = con.lastname, languagelocalekey = 'en_US',localesidkey = 'en_GB',contactId = con.Id,timezonesidkey = 'Europe/London',username = con.email,CommunityNickname = nick,ProfileId ='00e58000000NkUd', IsActive = true);
newUser1.setOptions(dmo); insert newUser1;

Can anyone please help me with how I can add this in my Test Class?

Thanks,

Tristan

 
Hey everyone! I'm still very new to Apex Code, but I've been trying to implement Chili Piper, and a portion of it allows you to automatically convert leads to contacts and opportunities: https://support.chilipiper.com/article/70-convert-lead-to-account-and-auto-create-an-opportunity-upon-booking-meeting

I've created a Sandbox environment, and built this Apex Class:
 
global class AutoConvertLeads implements Schedulable{

global Set<Id> LeadIds;

global void execute(SchedulableContext sc) {

LeadStatus Leads= [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
for(Id leadId : LeadIds){
Database.LeadConvert Leadconvert = new Database.LeadConvert();
Leadconvert.setLeadId(leadId);
Leadconvert.setConvertedStatus(Leads.MasterLabel);
Database.LeadConvertResult Leadconverts = Database.convertLead(Leadconvert);
System.assert(Leadconverts.isSuccess());
System.debug('LeadAssign Success');
}
System.abortJob(sc.getTriggerId());
}

public AutoConvertLeads (Set<Id> LeadIds) {
this.LeadIds=LeadIds;
}

}

Then I created this event trigger:
 
trigger ChangeTheOwnerAndConvert on Event (after insert) {
   Set<Id> LeadIds = new Set<Id>();
   for (Event e: Trigger.new){
   if (e.WhoId != null){
        String eventNameId = e.WhoId;
        if (!String.isBlank(e.Meeting_Type_CP__c)){
            if (e.Meeting_Type_CP__c.equals('Demo Request - Standard')){
                 LeadIds.add(e.WhoId);
                 Lead l = new Lead( Id = e.WhoId);
                 l.OwnerId = e.OwnerId;
                 update l;
                }
          }     
     }
   }
   if(LeadIds.size() > 0){
       Datetime sysTime = System.now();
       sysTime = sysTime.addSeconds(10);
       String chron_exp = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
       System.schedule('ConvertLead' + UserInfo.getUserId() + sysTime,chron_exp,new AutoConvertLeads(LeadIds));
   }
}

The Event Trigger is checked as "Is Active", but when I create a lead and create an event on that least with the Meeting Type = Demo Request - Standard, nothing happens.

Does anyone have insight into this? Would love any help!
Hi all,

I have two object: Events and Opportunities. What I would like to have happen is the following:

When the field Engineer__c is filled out on an Opportunity, I would like for the related Events field Client_Services__c field to be filled out with the same content. 

I know this will most likey be done with an Apex Trigger but I need some help with the code. In the past I have successfully done something similar but they were both the same object type. It seems the two different object types make it more complicated. 

Any insight would be appreciated.

Thanks,
Liz
Hey all, I have an after trigger that runs fine and everything updates correctly. But I'm not sure why on my test class it's not running when I systemAssert at the end. 

public class OpportunityHelper {
    public static void updateDistributions(map<Id, Opportunity> newMap, map<Id, Opportunity> oldMap){
        for(Id opportunityID : newMap.keyset()){
            //get donations with their related distributions
            List<Opportunity> distributionsID = [
                SELECT (SELECT Id FROM DistributionDonation__r) 
                FROM Opportunity 
                WHERE Id = :opportunityID
            ];
            
            //check if donation date changed
            if(oldMap.get(opportunityID).CloseDate != newMap.get(opportunityID).CloseDate){
                Date newDate = newMap.get(opportunityID).CloseDate;
                //updated all related distributions
                for(Opportunity Opp : distributionsID) {
                    for(Product_Distribution__c distribution : Opp.DistributionDonation__r){
                        distribution.Date_TBD__c = newDate;
                    }
                    update Opp.DistributionDonation__r;
                }
            }
}
}

@isTest
public class OpportunityHelperTest {
    static testMethod void testDateChange() {

        Test.startTest();

        Product_Distribution__c insertedTest = TestHelper.createRecords();

        Date newDate = Date.newInstance(2001, 01, 01);
        
        Opportunity opp = [SELECT ID, CloseDate From Opportunity Where ID =: insertedTest.Product_Donation_Name__c];

        opp.CloseDate = newDate;

        Test.stopTest();

        Product_Distribution__c dis = [Select ID, Product_Donation_Name__c, Date_TBD__c From Product_Distribution__c Where ID =: insertedTest.Id];
        
        System.assertEquals(opp.CloseDate, dis.Date_TBD__c);
        
    }
}

It always ends up not updating and instead just gets the date that was initalized with. 


System.AssertException: Assertion Failed: Expected: 2001-01-01 00:00:00, Actual: 2019-05-13 00:00:00
  • May 13, 2019
  • Like
  • 0
I've got an apex:chart that's rendering some data from a custom controller. 

I'm using an apex:barseries to display the data, and I've chosen to select stacked="true", which stacks two integer values onto the same column. 

The problem is, when you define the fields for that axis (in this case the right y axis), you give the axis a Title (i.e., Number of Customers), but when you display the Legend, there is no way to dicipher what each grouping in the stacked column represents. The Legend will just display the Title of the axis for each unique grouping. 

Does anyone know how to indicate a unique value for each group within the Legend? Thanks ~

User-added image

Hey everyone! I've been trying to implement this code snippet, but keep running into errors around Apex Identifiers:

 

Error: Compile Error: Invalid identifier '’00Q’'. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 6 column 36
 

Error: Compile Error: Invalid identifier '‘Demo'. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 7 column 45
 

Error: Compile Error: Invalid identifier '”'. Apex identifiers must start with an ASCII letter (a-z or A-Z) followed by any number of ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'. at line 17 column 27


Here is the code:

trigger ChangeTheOwnerAndConvert on Event (after insert) {
   Set<Id> LeadIds = new Set<Id>();
   for (Event e: Trigger.new){
   if (e.WhoId != null){
        String eventNameId = e.WhoId;
        if (eventNameId.startsWith(’00Q’) && !String.isBlank(e.Meeting_Type_CP__c)){
            if (e.Meeting_Type_CP__c.equals(‘Demo Request - Standard’)){
                 LeadIds.add(e.WhoId);
                 Lead l = new Lead( Id = e.WhoId);
                 l.OwnerId = e.OwnerId;
                 update l;
                }
          }     
     }
   }
   if(LeadIds.size() > 0){
       Datetime sysTime = System.now();
       sysTime = sysTime.addSeconds(10);
       String chron_exp = ” + sysTime.second() + ‘ ‘ + sysTime.minute() + ‘ ‘ + sysTime.hour() + ‘ ‘ + sysTime.day() + ‘ ‘ + sysTime.month() + ‘ ? ‘ + sysTime.year();
       System.schedule(‘ConvertLead’ + UserInfo.getUserId() +sysTime,chron_exp,new AutoConvertLeads(LeadIds));
   }
}

Does anyone know how to get around this? I'm very new to all of this still and took the code from this article: https://support.chilipiper.com/article/70-convert-lead-to-account-and-auto-create-an-opportunity-upon-booking-meeting


Thank you so much to anyone that can even attempt to help!
I have a parent component that iterates through a list of objects that are displayed in child components. Each child component has an input for an integer (default 0), and the parent component has an attribute that needs to be displayed as the sum of all child components' inputs.

What's the method of dynamically displaying the sum from the parent on change to any of the child components' input?
I have requirement to create a list view button on Accountcert object. That button just need to call the webservice  method. this is my requirement. 
that method need to pass parameters. how could i achieve this? this need to support in lightning as well
I pushed an Apex Class and Trigger to production but my TestClass is in sandbox, when the tests are run in production before deployment, does it run all tests from production, sandbox or both?
Hi,

I received a successful login in the SAML RESPONSE using SAML SSO (SP originated)

But I do not understand that why the SAML Response validator tool (in the SF website) returns the following:
invalid_grant, invalid assertion


What is wrong with the following SAML Reponse?

<?xml version="1.0" encoding="UTF-8"?> <samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Destination="http://zimit.dyndns.biz:5000/acs" ID="_b4f506626f60836832fec8afe3a6e43c1560292940423" InResponseTo="_97d26c1d-f354-4d98-af9f-e473a8021ed2" IssueInstant="2019-06-11T22:42:20.423Z" Version="2.0"> <saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://zimit-dev-ed.my.salesforce.com</saml:Issuer> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <ds:Reference URI="#_b4f506626f60836832fec8afe3a6e43c1560292940423"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"> <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="ds saml samlp xs xsi"/> </ds:Transform> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>psjhGPpxucOBnXvtzOJz6eP+QyM=</ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue> Q1TomO/zVxOFx89xE0wKg53CzFk6jfBk/hjbOILSIoZbgpbLWmLPUSUhQdVGFn4M1ofdw4gw7kbX in7Ir56TuKGqMINRfK9bzk52x+z1Ma9tp0bmSoSB6Si7U2GCrDMezDcU4T0zEm+zOPg1rgcE6Xit kndjpbXWSkwUvM2CTPkf8R5/5gIFGvAKmmGs6s4hyxs8ytAA4D31LOk4nT4gH/MFeyvcA+b5O8oy TkRmi4EX5dmzgVeLC/H5v2xCDsBsEKTwcRa5sIpu0xxslvqv7EQJKn9zYTpi0JTHfc9DR/NnWaQH 9PCBhi0f4njazX2jNZ6NqiDpfGkMxNyCi9rNeg== </ds:SignatureValue> <ds:KeyInfo> <ds:X509Data> <ds:X509Certificate>MIIEgTCCA2mgAwIBAgIOAWdQmsavAAAAADtTBpYwDQYJKoZIhvcNAQELBQAwgYIxGjAYBgNVBAMM EVppbWl0X1NTXzExXzI2XzE4MRgwFgYDVQQLDA8wMEQzNjAwMDAwMFp0SXExFzAVBgNVBAoMDlNh bGVzZm9yY2UuY29tMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQswCQYDVQQIDAJDQTEMMAoGA1UE BhMDVVNBMB4XDTE4MTEyNjE1MTkzOVoXDTE5MTEyNjEyMDAwMFowgYIxGjAYBgNVBAMMEVppbWl0 X1NTXzExXzI2XzE4MRgwFgYDVQQLDA8wMEQzNjAwMDAwMFp0SXExFzAVBgNVBAoMDlNhbGVzZm9y Y2UuY29tMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQswCQYDVQQIDAJDQTEMMAoGA1UEBhMDVVNB MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAutF5Z7nKVe57tAxckUjf3uU+5bzP7+8R NUNlmp49LKz9TQEHu98K8TRNjLll8LiyKWx1ETHQd7He5yo0Mb8TSLd+LZ+8lhw3BzO13/BrQWN6 4YBlaJptHCRWlKh/qjLZq2ctVztUZ8GkaUPM+Xu8gJYXxqOm4vcCeC0G0uKDHZFn23ZftLseFI2K 5krG3aFZX4SOOsFF0gyV2rynNpaaAFegShweqLY9cRGbjAGSaTT7BwFxU0cTrAUzDs7EsQYiOKIG jSDjqE4QR3FfSsSCP6a0KHT4WwHHzdNHTLcQo2BPnsnwI1f+eK03wRIkomqW2qtvK2XiYC/PjUqp 89ygnQIDAQABo4HyMIHvMB0GA1UdDgQWBBRDqm9UpG3NeCtbDE7/xTGup9ogpTAPBgNVHRMBAf8E BTADAQH/MIG8BgNVHSMEgbQwgbGAFEOqb1Skbc14K1sMTv/FMa6n2iCloYGIpIGFMIGCMRowGAYD VQQDDBFaaW1pdF9TU18xMV8yNl8xODEYMBYGA1UECwwPMDBEMzYwMDAwMDBadElxMRcwFQYDVQQK DA5TYWxlc2ZvcmNlLmNvbTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzELMAkGA1UECAwCQ0ExDDAK BgNVBAYTA1VTQYIOAWdQmsavAAAAADtTBpYwDQYJKoZIhvcNAQELBQADggEBAGBpLAJax4efGSlH 8V6M24q/6Tm5Li8S6/s925/LVjooqonqsqqsemaR13Bxq6GIszHOJIU1BiyB9kxnMcxFsOfyorR7 oNfc5RvfjSNn8QRHy/xpDBOtx/QBEuOWKPwDqV3fXiMStNEN3NMiX/t2RepnZle45tMiPi/vnWsa n9EnYxlNcRmfan+liRYL+KFsIY2BycyHugyzpMAwjsRZPYhPxYewtyQj0RUV3mb0wNgjiCDKydPX KmNDwTMb0a9erjEJ7twttBsE7/AwLNO3Y3a+Kbhh2+3LLxJ5DQmGZorfZoLz3dVJHYbLFO4y13mK wwSxIPoCRT+LjG3cfcu/0js=</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> </ds:Signature> <samlp:Status> <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/> </samlp:Status> <saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_729b075a9ae3301514cbeb7db39f204e1560292940423" IssueInstant="2019-06-11T22:42:20.423Z" Version="2.0"> <saml:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">https://zimit-dev-ed.my.salesforce.com</saml:Issuer> <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/> <ds:Reference URI="#_729b075a9ae3301514cbeb7db39f204e1560292940423"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"> <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="ds saml xs xsi"/> </ds:Transform> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/> <ds:DigestValue>aYZmrvjN40qDA0gB2Y7ml69YNms=</ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue> gcAkJTW8vY1E3pIY595NWPvNHKYQQwhXdIT5U8HheS/Q58WWkVbc1ef2wsYKHjOBBzJKC04YQu8J ODYxpB9sZ9PW3YyWwq6XJssmv9+H9J+n1jZL/yomZI98yTIwhmK/YY6YWW+lnLgMAcna0iqtb+la XqP+wNQnLhG3tuyIFkde4jNzg52ToS8ntPqTksVeXeJ0cdD73LyFJpxBVmCGtTMvkZrGgiMMIL4J Ysw5ny5mfTZf66vRsX5oUklHXP41Iluj/NQaNf4IiVYZHiQV1Paimvh4pDMWhszazZxpBhXWXHFw y43KwcagIbXI/1LRjYaovMAD63VkSnC8bOtqUA== </ds:SignatureValue> <ds:KeyInfo> <ds:X509Data> <ds:X509Certificate>MIIEgTCCA2mgAwIBAgIOAWdQmsavAAAAADtTBpYwDQYJKoZIhvcNAQELBQAwgYIxGjAYBgNVBAMM EVppbWl0X1NTXzExXzI2XzE4MRgwFgYDVQQLDA8wMEQzNjAwMDAwMFp0SXExFzAVBgNVBAoMDlNh bGVzZm9yY2UuY29tMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQswCQYDVQQIDAJDQTEMMAoGA1UE BhMDVVNBMB4XDTE4MTEyNjE1MTkzOVoXDTE5MTEyNjEyMDAwMFowgYIxGjAYBgNVBAMMEVppbWl0 X1NTXzExXzI2XzE4MRgwFgYDVQQLDA8wMEQzNjAwMDAwMFp0SXExFzAVBgNVBAoMDlNhbGVzZm9y Y2UuY29tMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMQswCQYDVQQIDAJDQTEMMAoGA1UEBhMDVVNB MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAutF5Z7nKVe57tAxckUjf3uU+5bzP7+8R NUNlmp49LKz9TQEHu98K8TRNjLll8LiyKWx1ETHQd7He5yo0Mb8TSLd+LZ+8lhw3BzO13/BrQWN6 4YBlaJptHCRWlKh/qjLZq2ctVztUZ8GkaUPM+Xu8gJYXxqOm4vcCeC0G0uKDHZFn23ZftLseFI2K 5krG3aFZX4SOOsFF0gyV2rynNpaaAFegShweqLY9cRGbjAGSaTT7BwFxU0cTrAUzDs7EsQYiOKIG jSDjqE4QR3FfSsSCP6a0KHT4WwHHzdNHTLcQo2BPnsnwI1f+eK03wRIkomqW2qtvK2XiYC/PjUqp 89ygnQIDAQABo4HyMIHvMB0GA1UdDgQWBBRDqm9UpG3NeCtbDE7/xTGup9ogpTAPBgNVHRMBAf8E BTADAQH/MIG8BgNVHSMEgbQwgbGAFEOqb1Skbc14K1sMTv/FMa6n2iCloYGIpIGFMIGCMRowGAYD VQQDDBFaaW1pdF9TU18xMV8yNl8xODEYMBYGA1UECwwPMDBEMzYwMDAwMDBadElxMRcwFQYDVQQK DA5TYWxlc2ZvcmNlLmNvbTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzELMAkGA1UECAwCQ0ExDDAK BgNVBAYTA1VTQYIOAWdQmsavAAAAADtTBpYwDQYJKoZIhvcNAQELBQADggEBAGBpLAJax4efGSlH 8V6M24q/6Tm5Li8S6/s925/LVjooqonqsqqsemaR13Bxq6GIszHOJIU1BiyB9kxnMcxFsOfyorR7 oNfc5RvfjSNn8QRHy/xpDBOtx/QBEuOWKPwDqV3fXiMStNEN3NMiX/t2RepnZle45tMiPi/vnWsa n9EnYxlNcRmfan+liRYL+KFsIY2BycyHugyzpMAwjsRZPYhPxYewtyQj0RUV3mb0wNgjiCDKydPX KmNDwTMb0a9erjEJ7twttBsE7/AwLNO3Y3a+Kbhh2+3LLxJ5DQmGZorfZoLz3dVJHYbLFO4y13mK wwSxIPoCRT+LjG3cfcu/0js=</ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> </ds:Signature> <saml:Subject> <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">etelmon@zimit.io</saml:NameID> <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"> <saml:SubjectConfirmationData InResponseTo="_97d26c1d-f354-4d98-af9f-e473a8021ed2" NotOnOrAfter="2019-06-11T22:47:20.423Z" Recipient="http://zimit.dyndns.biz:5000/acs"/> </saml:SubjectConfirmation> </saml:Subject> <saml:Conditions NotBefore="2019-06-11T22:41:50.423Z" NotOnOrAfter="2019-06-11T22:47:20.423Z"> <saml:AudienceRestriction> <saml:Audience>https://zimit-dev-ed.my.salesforce.com</saml:Audience> </saml:AudienceRestriction> </saml:Conditions> <saml:AuthnStatement AuthnInstant="2019-06-11T22:42:20.423Z"> <saml:AuthnContext> <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef> </saml:AuthnContext> </saml:AuthnStatement> <saml:AttributeStatement> <saml:Attribute Name="userId" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"> <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:anyType">00536000005dfvk</saml:AttributeValue> </saml:Attribute> <saml:Attribute Name="username" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"> <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:anyType">etelmon@zimit.io</saml:AttributeValue> </saml:Attribute> <saml:Attribute Name="email" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"> <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:anyType">etelmon@zimit.io</saml:AttributeValue> </saml:Attribute> <saml:Attribute Name="is_portal_user" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"> <saml:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:anyType">false</saml:AttributeValue> </saml:Attribute> </saml:AttributeStatement> </saml:Assertion> </samlp:Response>

Regards,

Emmanuel
Newbie

Ive looked through many pages (and bookmarked many) that show this and I've copied a very simple example, but it's not working.  I want to use an iframe to embed a salesforce lightning dashbaord on a visual force page.

I don't have much coding experience, but am confident I have enough knowledge to get this working.

My copied and edited code:

<apex:page standardController="Dashboard">

   <apex:iframe height="800px" width="600px" frameborder="true" rendered="true" scrolling="false"
	src="/01Z6A000000n28CUAQ?isdtp=nv" />

</apex:page>

The error message I get is that the sandbox domain refused to connect (researching this right now in case that's what the issue is).

Thanks!

I need to create a lightning component page to show Person details which is a custom object. I am able to to see the data when putting recordid value directly in lightning component but not able to get record Id value dynamically. here is my code

<aura:component implements="force:hasRecordId,force:hasSObjectName,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global">
    <aura:attribute name="recordId" type="String" access="public" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <lightning:recordViewForm recordId="{v.getRecordId}"
        objectApiName="Person__c">
    <div class="slds-grid">
        <div class="slds-col slds-size_2-of-3">
            <lightning:outputField fieldName="First_Name__c" />
            <lightning:outputField fieldName="Last_Name__c" />
        </div>
        <div class="slds-col slds-size_1-of-3">
            <lightning:outputField fieldName="Email__c" />
            <lightning:outputField fieldName="Home_Phone__c" />
        </div>
    </div>
</lightning:recordViewForm>
</aura:component>

Controller code:

doInit : function(cmp) {

    var recordId = cmp.get("v.recordId");
    var output = '{"record": "' + recordId + '"}';
    // alert('Recordid' +output);
    cmp.set("v.getRecordId", output);

It is showing record Id with above alert but component is not showing data.
What wrong I am doing ? I need to call this component from my person record page. I added this component by Edit Page.
Help is appreciated

Thanks,
Gaurav
 
can I run something to view the last time a list view was used/viewed? 
 workbench? 

Hi!

Have tried to get this to work for many hours now, but can't find a solution. I have written a cusom controller for a visualforce page that looks like the one below. And get 0% code coverage on the Apex Class.

Any idea what's wrong?

Controller:

public class outboundLeadStart {
    // ApexPages.StandardSetController must be instantiated
    // for standard list controllers
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT Id, Name, Company, Country, CreatedDate, Status FROM Lead WHERE Status='New' AND OwnerId= :UserInfo.getUserID() ORDER BY CreatedDate DESC LIMIT 100]));
            }
            setCon.setPageSize(setCon.getResultSize());
            return setCon;
        }
        set;
    }
    
    public integer getCountLeads() {
            String statusStage = 'New';
            String ownerId = UserInfo.getUserID();
            return(Database.countQuery('SELECT count() FROM Lead WHERE Status= :statusStage AND OwnerId= :ownerId')); // Returns Integer        
    }
    
    // Initialize setCon and return a list of records
    public List<Lead> getLeads() {
        return (List<Lead>) setCon.getRecords();
    }
    
    public PageReference save() {
        
        try {
            update setCon.getRecords();
        } catch(DMLException e) {
            Apexpages.addmessages(e);
        }
        
        PageReference pageRef = new PageReference('/lightning/n/Outbound_Planning');
        pageRef.setRedirect(true);
        return pageRef;        
    }    
}

And the test class looks like this:
@isTest
private class testoutboundLeadStartTest {
    static testMethod void testoutboundLeadStartTest() 
    {
        User u = new User(
            ProfileId = [SELECT Id FROM Profile WHERE Name = 'Sales Representative'].Id,
            LastName = 'last',
            Email = 'last@example.com',
            Username = 'last@example.com' + System.currentTimeMillis(),
            CompanyName = 'TEST',
            Title = 'title',
            Alias = 'alias',
            TimeZoneSidKey = 'America/Los_Angeles',
            EmailEncodingKey = 'UTF-8',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US'
        );
        
        insert u;
        
        Id theOwnerId = UserInfo.getUserID();
        
        ApexPages.StandardSetController setCon;
        PageReference pageRef = Page.outboundLeadsStart;
        
        List <Lead> addedLeads = new List<Lead>();
        
        Lead testLead = new Lead();
        testLead.LastName='Test Lead';
        testLead.Company='Test Company1';
        testLead.Status='New';
        testLead.OwnerId=theOwnerId;
        insert testLead;
        
        List<Lead> cus = new List<Lead>{};
            
        Test.startTest();
        System.assertEquals('Test Lead', testLead.LastName);
        Test.setCurrentPage(pageRef);
        outboundLeadStart controller = new outboundLeadStart();
        Test.stopTest();
        
    }        
}
 

Can't understand why this get 0% code coverage on the Apex Class.

BR,
Andreas


 

Hello,

I have a simple trigger to update a few custom fields on the User Profile Object. Not sure what is missing...I want my trigger to fire when the User Profile is updated.

Thanks for your help!

 

trigger Update_User_Custom_Fields_Trigger on User (before insert, before update) {
for(User u:trigger.new){
u.Last_Login_for_PB_Flows__c = u.LastLoginDate;
u.Managers_Email_for_PB_Flows__c = u.Managers_Email_del__c;
u.AboutMe = '*** This is a Test ***'
}
}

 

I have a visualforce page which has a datatable displaying a list of records. I would like the last column in this table to be a button which opens a popup/modal which will show further detail of this record. What is the best way to achieve this?
I am trying to mass update child records with a lightning quck action on the parent record detail page. Not sure what is wrong with this code. I appreciate your help.
Component 

<aura:component controller="MassUpdateController " implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
	<aura:attribute name="data" type="object__c[]"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="recordId" type="String"/>
    <!-- handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.init }"/>        
    <div style="height: 300px">
        <lightning:datatable
            columns="{! v.columns }"
            data="{! v.data }"
            keyField="id"                 
        />
    </div>
</aura:component>


Controller:

({
	
		init: function(cmp,event, helper) {
        cmp.set('v.columns', [
            {label: 'Name', fieldName: 'Name', type: 'text'  }            
          //  {label: 'Provider Email', fieldName: 'ProviderEmail', type: 'email', editable: true },
          //  {label: 'Not Associated to this Location', fieldName: 'NotAssociatedToThisLocation', type: 'checkbox' }
            
        ]);
        helper.fetchData(cmp,event, helper);        
	}
})


Helper

({
    fetchData: function (cmp,event,helper) {
        var RecordId = component.get("v.recordId");
        action.setParams({
        	"recordId" : RecordId
    	});
        var action = cmp.get("c.getRecords");
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var data = response.getReturnValue();
                cmp.set('v.data',data);
            }
            // error handling when state is "INCOMPLETE" or "ERROR"
        });
        $A.enqueueAction(action);
    }
})

Apex Controller

public class MassUpdateController {
	@AuraEnabled
    public static list<Managed_Care_Provider__c> getRecords(Id recordId){
        system.debug(' record Id ' + recordId);
        list<object__c> lstMC = [SELECT Id,Name from Object__c where Opportunity__c=: recordId];
        system.debug('---- list of MC ' + lstMC);
        return lstMC;
    }
}
I'm trying to rewrite some older visualforce pages that will work for both my lightning and classic users. I'd prefer using LWC since it is the recommended approach to new projects and much less complicated. However it does not work with Lightning out. Now that LWC is open-sourced, could I write an opensource LWC component and present it on both a lighting record page for lightning users as well as a VF page for classic users?
How to deep clone opportunity with related list custom object?
Suggest me the best solution, please.
Hello, I have a simple controller that I'd like to test. And the issue is that 'wrapobj.toAdjust' is not getting new value within test class. I'm relatively new to this - please advise. Thank you!

Controller:
public  with Sharing class INV_Audit_tool {
    
    Id whid;
    public list<wrapinv> wrapinvList { get; set; }
    public String WhName { get; set; }
 
    public INV_Audit_tool(){
        whid=ApexPages.CurrentPage().getparameters().get('id'); 
        //system.debug('whid==>'+whid);
        wrapinvList = new list<wrapinv>();
        
        List<Inventory__c> invList= [SELECT Id, WH_Real_Available__c, Product__c,  Product__r.Name, Product__r.Family, Warehouse_Location__c, Warehouse_Location__r.Name
                              FROM Inventory__c 
                              WHERE Warehouse_Location__c=:whid 
                              AND (Product__r.Family != 'COG PPE' AND Product__r.Family != 'COG PPE Scrap') 
                              ORDER BY Product__r.Name ASC];
        
        //system.debug('invList.size()==>'+invList.size());
        for(Inventory__c i : invList){
            
            wrapinvList.add(new wrapinv(i, 0));
            WhName = i.Warehouse_Location__r.Name;
        }
    }
    
    public PageReference save(){
        List <Inventory_Transaction__c > tranToInsert = new List <Inventory_Transaction__c >();
        for(wrapinv wrapobj : wrapinvList){
        system.debug('@@@@@ '+wrapobj);
            if(wrapobj.toAdjust > 0){
                 decimal difference = wrapobj.inv.WH_Real_Available__c - wrapobj.toAdjust;
                 
                 Inventory_Transaction__c tempInvTransObj = new Inventory_Transaction__c();
                 tempInvTransObj.Product__c = wrapobj.inv.Product__c;
                 tempInvTransObj.Warehouse_Location1__c = whid;
                 tempInvTransObj.Quantity__c = wrapobj.toAdjust;
                 tempInvTransObj.Overwrite_Existing_QoH__c  = true;
                 tempInvTransObj.Message__c = 'Audit: Old Quantity ' + wrapobj.inv.WH_Real_Available__c + ' Difference after audit: ' +  difference;
                 tranToInsert.add(tempInvTransObj);  
            }
        }
        try{ 
            if(tranToInsert.size()>0){
                insert tranToInsert;
            }
        }catch(Exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,''+e.getMessage()));   
        }
        PageReference redirectPG;
        redirectPG = new PageReference('/'+whid);
        return redirectPG;
    }
    
     public PageReference Cancel(){
        PageReference redirectPG;
        redirectPG = new PageReference('/'+whid);
        return redirectPG;
    } 
    
    public class wrapinv{
        public Inventory__c inv{get;set;}
        public decimal toAdjust{get;set;}
        
        public wrapinv(Inventory__c  i, Decimal adj){
            inv=i;
            toAdjust = adj;
        }
    }
}

Test:
@isTest
private class INV_Audit_tool_test {
    static testMethod void INV_Audit_tool() {
    
    Warehouse_Location__c wh = new Warehouse_Location__c();
    wh.name = 'test';
    insert wh;
    
    product2 prod = new product2();
    prod.Name = 'Test';
    prod.family = 'Absorbents 16Oz';
    insert prod;
    
    Inventory__c inv = new Inventory__c();
    inv.product__c = prod.id;
    inv.Qty_on_Hand__c = 100;
    inv.Qty_allocated__c = 0;
    inv.Warehouse_Location__c = wh.id;
    insert inv;
    
    
       
    test.StartTest();
    
    PageReference pageRef = new PageReference('/apex/INV_Audit_tool');
        pageRef.getParameters().put('id' , wh.id);
        Test.setCurrentPageReference(pageRef);
        INV_Audit_tool audit = new  INV_Audit_tool();

        INV_Audit_tool.wrapinv whObj = new INV_Audit_tool.wrapinv(inv, 5);
      
        audit.save();
        audit.cancel();
       
    test.StopTest();
    
    }
}
Here is test result: wrapobj.ToAdjust is not getting test value of 5. It stays 0.

User-added image
​​​​​​​
Hi Experts,
I have a requirement to add Multiple visualforce pages to combine as single page. This Visualforce pages are render as PDF. 
I want to create a new page like wizard where I need to display some vf pages and provide users to select the page and save. Once saved I need to attach them to record.

Kindly need inputs how can I approach.

Thanks.
Hello, 
I have just started learning SOQL and Apex programming concepts.  I need some help with retrieving results using SOQL query.  
The requirement is: to get all the records where Planning date__c is less than 14 days. 
Any help is appreciated. 

Thank you. 
Hi, 

I am trying to create a Lightning Component to that has a functionality to update a field value(Submit_Go_No_Go_Question__c), and hide the button whenever a field (Go_No_Go_Question__c) is not blank.

Here is my existing code

Apex:
public class addGNGQuestion {
    
    @AuraEnabled
    public static void updateChk(String key){
        Opportunity acc = [SELECT Id, Name, Submit_Go_No_Go_Question__c, Go_No_Go_Question__c FROM Opportunity WHERE Id=:key];  
        if(acc.Go_No_Go_Question__c == null){
            acc.Submit_Go_No_Go_Question__c = true;
        }
        UPDATE acc;
    }
}

Component:
<aura:component controller="addGNGQuestion"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:handler event="force:refreshView" action="{!c.isRefreshed}" />
    <div class="slds-align_absolute-center" style="height:12rem">
    <lightning:button variant="brand" 
                      label="Add Go-No Go Question" 
                      onclick="{!c.updateCheck}" 
                      aura:id="disablebuttonid" />
        </div>
</aura:component>

Controller:
({
    updateCheck : function(component, event, helper) {
        var rid = component.get("v.recordId");
        var action = component.get("c.updateChk");
        action.setParams({key : rid});
        action.setCallback(this, function(response) {
            var state = response.getState();
            
         let button = component.find('disablebuttonid');  
                 if(acc.Go_No_Go_Question__c != null){
            button.set('v.disabled',true)
            }
            
            if (state === "SUCCESS") {
                $A.get('e.force:refreshView').fire();  
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } 
                else {
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    isRefreshed: function(component, event, helper) {
        location.reload();
    },
})
Helper:
({
    updateCheck11_helper : function(c,e,h) {
        alert('Success!');
        var save_action = c.get("c.updateCheck");
        save_action.setParams({
            });
        $A.enqueueAction(save_action);
    }
})
Any help is much appreciated.
An <a> tag in the html file of the lwc is only adding the desired url to the current url of the community page that the lwc is in.
I have a requirement that ananymous user who doesn't requre login to access a page, fills the details, saves to an object (custom, and it has lookup field  to contact) . For this I have done the below steps
  • Added Domain
  • Created new Site
  • Assigned the created VF page in to the list 'Site Visualforce Pages'
  • Activated the site
  • Gave perrmissions (RWA) to the custom object
But when I click on the page I got the following error
Authorization Required

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