• Vishant Shah
  • NEWBIE
  • 305 Points
  • Member since 2014

  • Chatter
    Feed
  • 8
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 72
    Replies

Hi,

I have a trigger which copies all the values of fields from one object to another,

I want to add some text value to specific field followed by the value

Trigger Leadprocess on Lead_Object__c(after insert,after update)
{
     List<Lead> sub=new List<Lead>();
     for(Lead_Object__c v : Trigger.new)
     {
         
                   Lead  s = new Lead();
                  // s.RecordType.name =v.Record_Type__c;
                   s.FirstName=v.First_Name__c; 
                   s.LastName =v.Last_Name__c;
                   s.Account_Type__c = v.Account_Type__c;
                   s.Units_In_Inventory__c = v.Units_In_Inventory__c;
                   s.Company = v.company__c;
                   s.PostalCode = v.Billing_Zip__c; 
                   s.AnnualRevenue =v.Annual__c;
                   s.Salutation  = v.Salutation__c;
                   s.LeadSource =v.Record_Type__c;
                   s.Status =v.Leadstatus__c;
                   s.Additional_Information__c =v.ZID__c;  
                   sub.add(s);
           
           
            insert sub;
     }
}


Something like this,


s.Additional_Information__c ="The entered value is "+ v.ZID__c;

Please help me to know how to do this

Thanks in Advance
 

Any help with figuring out what the issue is here will be much appreciated. Thank you!

Trigger createPages on Contact (after insert, after update) {
List<Pages__c> p = new List <Pages__c> ();
For (Contact newContact: Trigger.New)

If (newContact.Pages_Read__c  > 0) {
p.add (new Pages__c (
Pages_Read__c = newContact.Pages_Read__c
Reading_Detail__c = newContact.Pages_Detail__c
Reader_Type__c = newContact.Reader_ID__c
Contact_Name__c = newContact.Name ) ) ;
pToInsert.add(p);

}
}
Try {
Insert pToInsert;
} catch (system.Dmlexception e) {
System.debug (e);
}
Hello Folks,

Actually this is more than a doubt than a discussion...

I've been working with Salesforce Development more than 03 years and I never get why to use ":" to do variables comparison, like the following :

Sample 1:
List<AnyObject__c> objC = [Select id FROM AnyObject__c WHERE year__c = '1994'];

Sample 2:
String yearSample = '1994';
List<AnyObject__c> objC = [Select id FROM AnyObject__c WHERE year__c =: yearSample];
Yes, I know the both Samples Work and I'm already accustomed to write this way... But it does really grinds my gears!!

Could anyone explain me why? And Kill my curiosity?

Wish all the best! Thank you in advance!

Hi all,

I have created the controller extension shown below, to add a visualforce page to my standard layout for a custom object.

Below is my controller, test class, and visualforce page. Right now, coverage is only 67%.

When I run the visualforce page that uses this extension, it works. How do I interrogate the value of “activePrograms” so I can bump up my coverage. Everything I’ve tried returns nulls.


public class DisplayActivePrograms {
               private final Call_Report__c callReport;
    
    public DisplayActivePrograms(ApexPages.StandardController stdController) {
        this.callReport = (Call_Report__c)stdController.getRecord();
    }

                public list<active_program__c> activePrograms;   
    public list<active_program__c>  getActivePrograms() {
        if (activePrograms == null) {
            activeprograms = [select
                                name,
                                category__r.name,
                                category__r.Category_Description__c,
                                start_date__c,
                                end_date__c
                 from active_program__c
                 where
                                end_date__c >= today];  
           
        }
       
        return activePrograms;
    }


@istest
public class DisplayActivePrograms_test {
  PUBLIC static @istest void DisplayActivePrograms_test() {
     account acct = new account(name='abc', phone = '999999999');
     insert acct;
     Call_report__c cr = new Call_report__c(call_date__c = date.newInstance(2014, 7, 1), customer__c=acct.id);
     insert cr;
     srp2__c cat = new srp2__c(name='123',category_description__c = '123 description');
     insert cat;
     date sdt = date.newInstance(2014, 6, 23);
     date edt = date.newInstance(2014, 8, 31);
     active_program__c ap = new active_program__c(name='test name for category 462', category__c=cat.id,start_date__c = sdt, end_date__c = edt);
     insert ap;
   
     ApexPages.StandardController sc = new ApexPages.standardController(cr);
     system.assert(sc != null);

  }
}



<apex:page standardcontroller="Call_Report__c" extensions="DisplayActivePrograms">
   <apex:pageBlock Title="Active Programs">
    <table width="100%">
        <tr>
        <td> <b>Program Name</b> </td>
        <td> &nbsp; </td>
        <td> <b>Category</b> </td>
        <td> &nbsp; </td>
        <td> <b>Category Name</b> </td>
        <td> &nbsp; </td>
        <td> <b>Start Date</b> </td>
        <td> &nbsp; </td>
        <td> <b>End Date</b> </td>
        </tr>
        <tr>
        <td colspan="9"> <hr/> </td>
        </tr>
    <apex:repeat value="{!activePrograms}" var="a">
       
        <tr>
            <td> {!a.Name} </td>
                    <td> &nbsp; </td>
            <td> {!a.Category__r.name} </td>
                    <td> &nbsp; </td>
            <td> {!a.Category__r.Category_Description__c} </td>
                    <td> &nbsp; </td>
            <td><apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                <apex:param value="{!a.Start_Date__c}" />
                </apex:outputText> </td>
                        <td> &nbsp; </td>
            <td><apex:outputText value="{0,date,MM'/'dd'/'yyyy}">
                <apex:param value="{!a.End_Date__c}" />
                </apex:outputText> </td>
           
        </tr>
    </apex:repeat>
        </table>

    </apex:pageBlock>
</apex:page>
For a Master-Detail or Look Up relationship. First query simply matches ID (for lookup or master-detail field) whereas second one gets all records of detail from Master ID record. So, at last both will return same records. Only fetching them will be little different. So, which one should I use and which one will give better performance?

[select id, DetailObjField__c from DetailObj__c where Master__c=:MasterId]

OR

[select id,(select DetailObjField__c from DetailObj__r) from Master__c where Master__c.id=:MasterId]
Hi,

I'm writing a trigger to create an event whenever a campaign member is created, but I've hit an issue I don't understand.

This is the trigger:

trigger CreateEventforCampaignMember on CampaignMember (after insert) {

    // 1. create a list of events
    List <Event> eventsToInsert = new List <Event>();
    
    User usr = [SELECT Id FROM User WHERE FirstName =: 'Mark' AND LastName =: 'Alger' AND IsActive = TRUE LIMIT 1];
    // This is to ensure that all events belong to Mark.
    
    // 2. for every campaign member being inserted, add to the list of events (this is so that the trigger can handle bulk inserts)
    for (CampaignMember cm : trigger.new) {
        eventsToInsert.add(
                            new Event    (
                                            EndDateTime = cm.End_Date_of_Event__c,
                                            IsPrivate = false,
                                            IsRecurrence = false,
                                            IsReminderSet = false,
                                            OwnerID = usr.Id,
                                            ActivityDate = cm.Date_of_Event__c,
                                            StartDateTime = cm.Date_of_Event__c,
                                            Subject = cm.Subject__c,
                                            WhoID = cm.LeadId
                                        )
        );
    }
    
    // 3. insert the list of events
    insert eventsToInsert;
}

This is the error I get when I try to save the trigger:

Error: Compile Error: Invalid initial expression type for field Event.ActivityDate, expecting: Date at line 18 column 60

Any help would be very much appreciated!
Hello,
I've written a trigger that updates an opportunity to Closed Won and sets a value (NetSuite Sales Order ID) in a custom opp field based on a related Sales Order case being updated with certain values (NetSuite Sales Order ID) and the case being closed. The trigger works great and updates values on the Opp as expected, but I'm either facing errors in my test class or running into other code/validations because I'm setting the opp to Closed Won. If it's the former, I'd appreciate any help or suggestions on how better to structure my test class and/or my trigger. If it's the later, is there anything I can put in my code to see what other code or validations are causing the problem?

I continue to get errors like this when I run the test class:
System.AssertException: Assertion Failed: Expected: Pending Sales Order, Actual: Closed Won
OR (if I comment out the line causing the above issue)
System.AssertException: Assertion Failed: Expected: 12345, Actual: null

Here's my trigger:
trigger SalesOrderUpdateStageToClosedWon on Case (after Update) {
List<Opportunity> oppList=new List <Opportunity>();
set<id> oppIds = new Set<id>();
RecordType rt = [SELECT Id,Name,SobjectType FROM RecordType WHERE Name = 'Sales Order Case' AND SobjectType = 'Case' LIMIT 1];

for(case c:trigger.new)
{
oppIds.add(c.Opportunity__c);
}
Map<id,Opportunity>oppMap=new Map<id,Opportunity>([Select Id from Opportunity 
Where id in :oppIds]);
List<case> myCases = [select ID from case where ID in :oppIds]; 
Set<ID> myOppsIDs = new Set<ID>();

for (case c : myCases)
{
myOppsIDs.add(c.Opportunity__c);
}
for (case c :trigger.new)
{
if(c.RecordTypeId==rt.Id&&c.NetSuite_Sales_Order_ID__c <> null&&c.Status=='Closed'){
opportunity opp=oppMap.get(c.Opportunity__c);
opp.StageName='Closed Won';   
opp.NetSuite_Sales_Order_ID__c=c.NetSuite_Sales_Order_ID__c;       
oppList.add(opp);
}


}

update oppList;
}


And here's my test class:
@isTest (SeeAllData=True)
public class SalesOrderUpdateStageToClosedWon_Test{

    
    static testMethod void testOppClosedWon(){ 
    test.startTest();  
    //Create Account and Opportunity Record
    Date dToday = Date.today();
    Account acc = new Account(Name = 'Test Account');
    insert acc;
    Opportunity oppRec = new Opportunity (Name = 'Test Opportunity', AccountId = acc.Id, StageName='Pending Sales Order', 
    CloseDate=dTODAY,Ship_Date__c=dTODAY+1,Customer_Notes_Completed__c=true,Approval_Status__c='Approved',
                                          Number_of_Locations__c = 1,Renewal_Term_months__c=1,RecordTypeID='012R0000000DBjt');
     insert oppRec;
        
    //Create Case
  
    
   
    
    Case caseRec = new Case(Opportunity__c = oppRec.Id, POS_Install_Date__c=Date.newInstance(2014,12,31),RecordTypeID='012R00000004y6K',Status='Closed',NetSuite_Sales_Order_ID__c='12345');
    system.debug('About to insert Case' + caseRec);
    insert caseRec;
    
    
    System.Debug('Value of Insert Opp ID ------------------------>' + oppRec.Id);
    System.Debug('Value of Insert Opp StageName ------------------------>' + oppRec.StageName);   
    
    Case testCase = [Select Opportunity__c,NetSuite_Sales_Order_ID__c from Case where Id =: caseRec.Id];
    Opportunity testOpp = [Select Id,StageName, CloseDate,NetSuite_Sales_Order_ID__c from Opportunity where Id =: oppRec.Id];
    
    //Id caseRecId = caseRec.OpportunityId;
    System.assertEquals(testOpp.Id, testCase.Opportunity__c);
    System.assertEquals(testOpp.StageName,'Closed Won');
    System.assertEquals(testCase.NetSuite_Sales_Order_ID__c,testOpp.NetSuite_Sales_Order_ID__c);
    test.stopTest();
    }
    
}



Hello,

I have a test class that currently covers multiple triggers.  How can I get this calss to cover only 1 trigger?  It's causing an issue because some of the triggers are Before Insert triggers and others are After Insert so I am getting Null Pointer Exception errors because of it.  Thanks,
  • June 13, 2014
  • Like
  • 0
Hi,

I am being asked to find out how long does salesforce store notes and attachments, Is it a case of lifetime till we have our org or a n number of years?

Please let me know as soon as you can.

Ta
Vish
Hi there,

Has anyone experienced performance issue with developer console on CS7, via chrome. I just cannot save anything or even look at code since the summer 14 release on this instance.

Vish
Hi Community,

In our org we have a schedule job that is supposed to execute everyday at 6pm and another at 8 pm. the job that runs at 6pm doesnot execute and the job at 8pm executes without fail. I have checked the settings of the schedule and it is set to run everyday as the job at 8pm.

Does anyone out here have any indications as to what it could be

Thanks
Vishant
Hi,

I've got  a scheduled job  for invoicing, using financial force, which starts off a batch job based on SOQL query filters, When this batch job finishes, there is a check to see if there are any more records that need processing and executes the same batch using database.execute.

when the first batch runs the process finishes quite fast, but the next batch takes about 5 minutes to process. I am aware that the batch execution is dependant on salesforce resources, but 5 minutes is too long. I've tried rescheduling instead of executing the batch but this takes similar amount of time.

Is there a optimised or a better solution to do this sort of thing. this is the piece of code in my finish method of the batchable class.

Datetime sysTime = System.now().addSeconds( 10 );
String chronExpression = '' + sysTime.second() + ' ' + sysTime.minute() + ' ' + sysTime.hour() + ' ' + sysTime.day() + ' ' + sysTime.month() + ' ? ' + sysTime.year();
               
AutoInvoiceSchedule aib = new AutoInvoiceSchedule();
System.schedule( 'EmailInvoicesBatchSchedule ' + sysTime, chronExpression, aib );

Look forward to your replies.

Thanks
Vishant

Hi,

I am being asked to find out how long does salesforce store notes and attachments, Is it a case of lifetime till we have our org or a n number of years?

Please let me know as soon as you can.

Ta
Vish
I want to clean up my sandbox(delete bulk classes, objects,triggers etc). can any one guide me....Thanx in advance
Hi All,
I have a trigger onUpdate & onBefore for Opportunities.
When it's triggered, it reads a opportunity field and updates the owner of the opportunity.

It works fine with any change I do on the opportunity, except if I change the owner.

In the debug log I can see that the trigger is fired, and it change the owner, but the opportunity finally doesn't have the owner assigned in the trigger but the owner that I have selected with the lookup.

Any help?

Thanks in advance
Hello I'm using JS to create error messages when a field is blank ...

This works for InputText:

if(document.getElementById("{!$Component.theform.block01.nomJobIP}").value == "" ||
document.getElementById("{!$Component.theform.block01.mailIP}").value == "" ||
document.getElementById("{!$Component.theform.block01.nomJobIP}").value == "")
{
    alert("messsage");
}

To CHECK BOX and SELECT OPTION does not work.
Why????
if(document.getElementById("{!$Component.theform.block01.ckLun}").checked == false &&
document.getElementById("{!$Component.theform.block01.ckMar}").checked == false &&
document.getElementById("{!$Component.theform.block01.ckMer}").checked == false &&
document.getElementById("{!$Component.theform.block01.ckJeu}").checked == false &&
document.getElementById("{!$Component.theform.block01.ckVen}").checked == false &&
document.getElementById("{!$Component.theform.block01.ckSam}").checked == false &&
document.getElementById("{!$Component.theform.block01.ckDim}").checked== false
){
    alert("messsage");
}

var aa = document.getElementById("{!$Component.theform.block01.selMoisFreqSem}").value;
var bb = document.getElementById("{!$Component.theform.block01.selMoisFreq}").value;

if(aa == '' && bb == '' || aa == null && bb == null)
{
    alert("select NULL");
}

Thank you!!!!
Receiving 2 x initial mail instead of one
Description Hi, I have written a trigger based workflow which will send one acknowledgment to the Customer with an template. Problem is same mail is sending twice to the customer. Anyone help me to get it solve. It will be highly appreciated.
please see the code snippet

trigger sendEmail on Case (after insert,after update) {
    Public static Boolean InitialEmail =false;
    Public Static Boolean FinalEmail =false;
   
    for(Case c:trigger.new) {
       
        system.debug('outside'+c.Send_Email_to_Contact__c);
       
        if ((trigger.isInsert || (trigger.oldMap.get(c.Id).Send_Email_to_Contact__c != c.Send_Email_to_Contact__c)) && (c.Send_Email_to_Contact__c && !c.Do_not_Send_Email__c  && c.Email_of_Complainant__c!=null && c.Status!='Completed')) {
               
                system.debug('??????'+c.Send_Email_to_Contact__c);
              
                    sendEmailMessage(c.id,c.ownerId,c.Internal_Comments__c,c.Email_of_Complainant__c,c.Site_Details__c,c.CaseNumber,c.Case_Customer_Reference__c );
        }
       
       
       
        if ((trigger.isInsert || (trigger.oldMap.get(c.Id).Status != c.Status)) && (c.Final_email_to_contact__c && !c.Do_not_Send_Email__c  && c.Email_of_Complainant__c!=null && c.Status=='Completed')) {
               
                system.debug('****************'+c.Send_Email_to_Contact__c);
               
                sendFinalEmailMessage(c.id,c.ownerId,c.Internal_Comments__c,c.Email_of_Complainant__c,c.Site_Details__c,c.CaseNumber,c.Case_Customer_Reference__c);
        }
       
   
    }
   
    public void sendEmailMessage(String CaseId,String ConId,String internalComments,String EmailOfComplaint,String SiteDetail,String CaseNumber,String CustRef){
           
            Messaging.reserveSingleEmailCapacity(2);

            // Processes and actions involved in the Apex transaction occur next,
            // which conclude with sending a single email.
           
            // Now create a new single email message object
            // that will send out a single email to the addresses in the To, CC & BCC list.
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           
            // Strings to hold the email addresses to which you are sending the email.
           
            String[] toAddresses = new String[] {EmailOfComplaint};
          //  String[] ccAddresses = new String[] {'koushik.saha@wipro.com'};
            String[] BccAddresses = new String[] {'Opsinvestigationteam@thameswater.co.uk'}; 
           
            // Assign the addresses for the To and CC lists to the mail object.
            mail.setToAddresses(toAddresses);
          //  mail.setCcAddresses(ccAddresses);
            mail.setBccAddresses(BccAddresses);
           
            // Specify the address used when the recipients reply to the email.
            mail.setReplyTo('OnlineCustomers@thameswater.co.uk');
           
            // Specify the name used as the display name.
            mail.setSenderDisplayName('OnlineCustomers@thameswater.co.uk');
           
            // Specify the subject line for your email address.
            mail.setSubject('Case Customer reference :'+CustRef+ ': Site Address :'+ SiteDetail + ': Query Number :'+CaseNumber);
           
            // Set to True if you want to BCC yourself on the email.
            mail.setBccSender(false);
           
            // Optionally append the salesforce.com email signature to the email.
            // The email address of the user executing the Apex Code will be used.
            mail.setUseSignature(false);
           
            // Specify the text content of the email.
            //mail.setPlainTextBody('Your Case: ' + case.Id +' has been created.');

          //  mail.setTargetObjectId('003P000000ZdOsB');
            mail.setWhatId(CaseId);
          //  mail.setTemplateId('00XP0000000I3cA');
           
           
            mail.setHtmlBody('<table><tr><td><img align="right" src="https://c.cs4.content.force.com/servlet/servlet.ImageServer?'+
            'id=015P00000000x8T&oid=00DP00000006dHM"/></td></tr><tr><td><br/><p><span style="font-family: Calibri;font-size=12pt;">'+
            '<font color="#333333">Dear Sir/Madam,</font></span></p>'+
            '<p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">Thank you for your enquiry on the above '+
            'address.</font></span></p><p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">'+
            'We would like to confirm that this query is currently being investigated and we will respond within 5 working days. '+
            '</font></span></p><p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">In the meantime, if you need anything further please contact '+
            'us on 0845 070 9148 and our team will be happy to help.</font></span></p></td></tr><tr><td><br/><br/><br/><br/></td></tr>'+
            '<tr><td><img src="https://c.cs4.content.force.com/servlet/servlet.ImageServer?id=015P00000000qUj&oid=00DP00000006dHM"/></td></tr></table>');

     //            'To view your case <a href=https://na1.salesforce.com/'+case.Id+'>click here.</a>');
    
       
            // Send the email you have created.
            if(!Test.IsRunningTest())
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

       
        }
       
     public void sendFinalEmailMessage(String CaseId,String ConId,String internalComments, String EmailOfComplaint,String SiteDetail,String CaseNumber,String CustRef){
           
            if(internalComments==null){
            internalComments='';
            }
            Messaging.reserveSingleEmailCapacity(2);

            // Processes and actions involved in the Apex transaction occur next,
            // which conclude with sending a single email.
           
            // Now create a new single email message object
            // that will send out a single email to the addresses in the To, CC & BCC list.
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
           
            // Strings to hold the email addresses to which you are sending the email.
            String[] toAddresses = new String[] {EmailOfComplaint};
       //     String[] ccAddresses = new String[] {'koushik.saha@wipro.com'};
            String[] BccAddresses = new String[] {'Opsinvestigationteam@thameswater.co.uk'}; 
           
            // Assign the addresses for the To and CC lists to the mail object.
            mail.setToAddresses(toAddresses);
         //   mail.setCcAddresses(ccAddresses);
            mail.setBccAddresses(BccAddresses);
           
            // Specify the address used when the recipients reply to the email.
            mail.setReplyTo('OnlineCustomers@thameswater.co.uk');
           
            // Specify the name used as the display name.
            mail.setSenderDisplayName('OnlineCustomers@thameswater.co.uk');
           
            // Specify the subject line for your email address.
            mail.setSubject('Case Customer reference :'+CustRef+ ': Site Address :'+ SiteDetail + ': Query Number :'+CaseNumber);
           
            // Set to True if you want to BCC yourself on the email.
            mail.setBccSender(false);
           
            // Optionally append the salesforce.com email signature to the email.
            // The email address of the user executing the Apex Code will be used.
            mail.setUseSignature(false);
           
            // Specify the text content of the email.
            //mail.setPlainTextBody('Your Case: ' + case.Id +' has been created.');

       //     mail.setTargetObjectId('003P000000ZdOsB');
            mail.setWhatId(CaseId);
       //     mail.setTemplateId('00XP0000000I3cA');
           
           
       
mail.setHtmlBody('<table><tr><td><img align="right" src="https://c.cs4.content.force.com/servlet/servlet.ImageServer?'+
            'id=015P00000000x8T&oid=00DP00000006dHM"/></td></tr><tr><td><br/><p><span style="font-family: Calibri;font-size=12pt;">'+
            '<font color="#333333">Dear Sir/Madam,</font></span></p>'+
            '<p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">Further to your enquiry on the above address.'+
            '</font></span></p><p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">'+
            'We\'ve completed our investigations and can provide the following response: '+
            '</font></span></p><p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">'+internalComments+'</font>'+
            '</font></span></p><p><span style="font-family: Calibri;font-size=12pt;"><font color="#333333">If you have any further questions please contact us on 0845 070 9148.</font></span></p></td></tr><tr><td><br/><br/><br/><br/></td></tr>'+
            '<tr><td><img src="https://c.cs4.content.force.com/servlet/servlet.ImageServer?id=015P00000000qUj&oid=00DP00000006dHM"/></td></tr></table>');


          
            // Send the email you have created.
            if(!Test.IsRunningTest())
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

       
        }
}
Hii
My error messages do not work.
I have a method within this method and use the code below:

APEX CONTROLLER:
global PageReference schedulejob(){
..............................
if (nomJob == null){
    ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'job null');
    ApexPages.addMessage(myMsg);
    }
    else

        system.schedule(NomJobSchedulable , expression, p);
..............

PageReference pageRef = new PageReference('/apex/BBBBPage');
        pageRef.setRedirect(true);
        return pageRef ;
}

Inside the Visualforce page, the button will execute this method that contains the error message, but does not work. why?

..........
<apex:PageBlock id="block01">
  <apex:pagemessages id="showmsg" />

.............

Nom Job.:&nbsp;<apex:inputText id="nomJobIP" value="{!nomJob}" />

...................

 <apex:commandButton value="Create" action="{!schedulejob}"/>



Hi,

I have a trigger which copies all the values of fields from one object to another,

I want to add some text value to specific field followed by the value

Trigger Leadprocess on Lead_Object__c(after insert,after update)
{
     List<Lead> sub=new List<Lead>();
     for(Lead_Object__c v : Trigger.new)
     {
         
                   Lead  s = new Lead();
                  // s.RecordType.name =v.Record_Type__c;
                   s.FirstName=v.First_Name__c; 
                   s.LastName =v.Last_Name__c;
                   s.Account_Type__c = v.Account_Type__c;
                   s.Units_In_Inventory__c = v.Units_In_Inventory__c;
                   s.Company = v.company__c;
                   s.PostalCode = v.Billing_Zip__c; 
                   s.AnnualRevenue =v.Annual__c;
                   s.Salutation  = v.Salutation__c;
                   s.LeadSource =v.Record_Type__c;
                   s.Status =v.Leadstatus__c;
                   s.Additional_Information__c =v.ZID__c;  
                   sub.add(s);
           
           
            insert sub;
     }
}


Something like this,


s.Additional_Information__c ="The entered value is "+ v.ZID__c;

Please help me to know how to do this

Thanks in Advance
 

Hi,

I am getting error while parsing datetime field in test class.My controller is working fine:
As I have given below code:
public pagereference saveOpportunity(){
String bcontact='';
String serializedDate = ApexPages.currentPage().getParameters().get('bcontact');
        System.debug('*************'+serializedDate);
       
        if(serializedDate!=''){
         dt = DateTime.parse(serializedDate);
         System.debug('*************'+dt);
        }
}
In test class I am writing :
Datetime nowdate=System.now();
        string strfromdate = nowdate.format();
        system.debug('startdate :' + strfromdate );
        datetime startdate = datetime.parse(strfromdate);
        system.debug('startdate :' + startdate);
        oppn.Best_Time_To_Contact__c=startdate ;
I am able to fetch oppn.Best_Time_To_Contact__c properly and also able to insert opportunity record.But when I am calling apex function  dScript.saveOpportunity(),
I am getting this error:

System.NullPointerException: Argument cannot be null.
Can anybody please help me where I am getting issue and how to resolve this issue ASAP.
I keep getting this error on one of my working triggers. Would anyone know how to stop the error System.Exception: Too many SOQL queries: 101 from occurring?

trigger Trigger_EventBeforeInsertUpdate on Event (before insert, before update) {
   
    /** Add **/
    Set<Id> whoIds = new Set<Id>();
    for(Event event: System.Trigger.New){
        whoIds.add(event.whoId);
    }
   
    Map<Id, Contact> contactMap = new Map<Id, Contact>([select Id,Name from Contact where Id in:whoIds]);
    Map<Id, Lead> leadMap = new Map<Id, Lead>([select Id,Name from Lead where Id in:whoIds]);
    /** Add **/
   
   
    for(Event event: System.Trigger.New){
        List<sObject> lobjects;
        string name;
        lobjects = [select Id, Name from Account where Id=:event.WhatId];
        if(lobjects.size() == 1)
            name = ((Account)lobjects[0]).Name;
        else{ 
            lobjects = [select Id, Name from Opportunity where Id=:event.WhatId];
            if(lobjects.size() == 1)
                name = ((Opportunity)lobjects[0]).Name;
            else{ 
                lobjects = [select Id, CaseNumber from Case where Id=:event.WhatId];
                if(lobjects.size() == 1)
                    name = ((Case)lobjects[0]).CaseNumber;
                else{
                    lobjects = [select Id, Name from Campaign where Id=:event.WhatId];
                    if(lobjects.size() == 1)
                    name = ((Campaign)lobjects[0]).Name;
                }
            }     
        }
       
        /**Add**/        
        if (contactMap.containskey(event.whoId) == true) {
            event.Description = 'Related To: ' + name + '\n Contact Name:' + contactMap.get(event.whoId).Name +'\n'+  event.Activity_Comment__c;
        } else if (leadMap.containskey(event.whoId) == true) {
            event.Description = 'Lead Name:' + leadMap.get(event.whoId).Name +'\n'+  event.Activity_Comment__c;
        }
                    
        System.debug('description is set to ' + event.Description);
    }
}
  • June 26, 2014
  • Like
  • 0
Hello All,
I am trying to delete more then one record from custom object and trying to pass a collection as an parementer to query.  I can delete individual record with hard coded value however if i pass a paramenter for single value or collection its not deleteing and not returing any records from query.  below is the code for your reference.  your early help will be appreciated.

Set<String> demNames = new Set<String>();
        String strVal;             
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');         
         
            demNames.add(inputvalues[0]);
         
        }
        try{
            //display dats from set string
            String str1 = String.join(new List<String>(demNames),'--');

            ApexPages.addMessage( new ApexPages.Message(ApexPages.severity.ERROR,Str1));

     TempDems__c[] d = [SELECT Name FROM TempDems__c WHERE Name IN :demNames] ;          
            ApexPages.addMessage( new ApexPages.Message(ApexPages.severity.ERROR,string.valueof(d.size())));
            delete d;

// Below code is working if i hard code the value
     //TempDems__c a =[SELECT Name FROM TempDems__c WHERE Name ='D-1234569'];
            //delete a;
           
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }

Please let me know if you find any issues in above code.

Thanks,
Ved
For a Master-Detail or Look Up relationship. First query simply matches ID (for lookup or master-detail field) whereas second one gets all records of detail from Master ID record. So, at last both will return same records. Only fetching them will be little different. So, which one should I use and which one will give better performance?

[select id, DetailObjField__c from DetailObj__c where Master__c=:MasterId]

OR

[select id,(select DetailObjField__c from DetailObj__r) from Master__c where Master__c.id=:MasterId]

Hey everyone, I've got this Apex class that I swear should work:

 

Global class Page1TaskReadyTriggerDate implements Schedulable {
  global void execute (Schedulablecontext SC){
    
    Page1Task__c[] tasksToUpdate = new Page1Task__c[]{};
    
  date myDate = system.today();
  
  Page1Task__c[] readyTasks = ([SELECT ID, Status__c FROM Page1Task__c 
                WHERE Ready_Trigger_Date__c != NULL
                AND Ready_Trigger_Date__c <= :myDate
                AND Status__c = '1) Not Started']);
          
  for (Page1Task__c rt : readyTasks){
    if (rt.Status__c != null){
    rt.Status__c = '2) Ready';
    tasksToUpdate.add(rt);      
    }
  }
  
  
  update tasksToUpdate;
  
  }
}

 

When I use the baked-in apex scheduler in Salesforce, it will run on the day I set it - but fails on subsequent days. For instance, I set it to run each day at 6am. It will run that day at 6am and set all of my fields accordingly. It fails on subsequent days. Is there something I'm missing or should this be rewritten?

 

Edit: It actually only runs the day the class was generated. It's not getting the system date on subsequent days, Creating a second scheduled apex job results in nothing, but rebuilding the class and scheduling works fine.

  • August 06, 2012
  • Like
  • 1