• Sumit 61
  • NEWBIE
  • 110 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 7
    Likes Received
  • 0
    Likes Given
  • 87
    Questions
  • 59
    Replies
When I running batch class its not covering excute method and giving 38%
 
global class Batch implements Database.Batchable<sObject>, Schedulable  {
    public static final String STATUS_SCHEDULED = 'Scheduled';  
    public static final String STATUS_SUBMITTED = 'Submitted';

    public static final Set<String> SET_SUBMITTED_TIMECRAD_STATUS =  new Set<String>{STATUS_SUBMITTED, STATUS_APPROVED, STATUS_REJECTED};
        
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query ='SELECT Id, Name,Contact__c, Contact__r.Email ,Contact__r.Name, ';
               query += ' (SELECT Id FROM Contact__r WHERE Start_Date__c = LAST_N_DAYS:12 AND Status__c IN: SET_SUBMITTED_TIMECRAD_STATUS )';
               query += ' FROM Account WHERE Status__c =: STATUS_SCHEDULED AND Contact__c != NULL';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope) {
		
		Map<Id,Account> contactIdWithAssigment = new Map<Id,Account>();		
		
		for(Account  assigment : scope) {
		   if(assigment.Contact__r.size() == 0) {
		   	 contactIdWithAssigment.put(assigment.Contact__c, assigment); 
		   }									        	
		}
        
        String startDate = Date.Today().addDays(-6).format();
        String endDate = Date.Today().format();
        MTX_TimecardReminder_Uitility.sendTimecardReminder('Timecard_Reminder_Template', contactIdWithAssigment, startDate, endDate);
    }
    
    global void finish(Database.BatchableContext BC) {      
  	}
  	
  	global void execute(SchedulableContext sc) {
        MTX_TimecardReminder_Batch timecardReminder = new MTX_TimecardReminder_Batch(); 
        database.executebatch(timecardReminder);
    }
}
 
@isTest
public class test_Batch_Test {
    
    @testSetup 
    static void setup() {
        List<Project__c> dem = new List<Project__c>();
        List<Account> acc = new List<Account>();
        List<Contact> con = new List<Contact>();
        
        // insert 10 records
        for (Integer i=0;i<10;i++) {
            dem.add(new Project__c(name='Project '+i, 
                Project_Stage__c ='New'));
        }
        insert dem;
        
        for (Project__c demByList : [SELECT Id from Project__c]){
			acc.add(new Account(Name = 'TestName', Status__c = 'Scheduled',
                 Project__c=demByList.id));
        }
        insert acc;
        
        for (Account accByList : [SELECT Id,Project__c from Account]){
			con.add(new Contact(AccountId = accByList.Id,
                 Status__c = 'Submitted', Start_Date__c = System.today() - 12,
                 Project__c=accByList.Project__c));
        }
        insert con;
        

        
    }
    
    static testmethod void test() {        
        
        Test.startTest();
        test_Batch trb = new test_Batch();
        Id batchId = Database.executeBatch(trb, 200);
        Test.stopTest();

    }


}

 
Getting error on Line no 13.
  1. public class CloneInternshipOpportunity {
  2.    
  3.     public static void createInternshipOpportunity(List<alu_Internship_Cycle__c> internCycle) {
  4.         /*try{*/
  5.             
  6.             Map<Id,alu_Internship_Cycle__c> mapIdbyNewInternCyc = new  Map<Id,alu_Internship_Cycle__c>(internCycle);
  7.             System.debug('mapIdbyNewInternCyc'+mapIdbyNewInternCyc);
  8.  
  9.             Map<Id,alu_Internship_Cycle__c> mapIdbyOldInternCyc = new Map<Id,alu_Internship_Cycle__c> ([
  10.                 SELECT Id, Name, Start_Date__c 
  11.                 FROM alu_Internship_Cycle__c 
  12.                 WHERE Id NOT IN: mapIdbyNewInternCyc.keySet() 
  13.                 AND Start_Date__c =: mapIdbyNewInternCyc.values().Start_Date__c.addYears(-1)]);
  14.             
  15.             System.debug('mapIdbyOldInternCyc '+mapIdbyOldInternCyc);
  16.             
  17.             List<Opportunity> oppListByOldCyc = [
  18.                 SELECT id, Name, RecordTypeId, AccountId, Account.Name, Internship_Cycle__c, Internship_Cycle__r.Name, CloseDate,  StageName 
  19.                 FROM Opportunity 
  20.                 WHERE Internship_Cycle__c IN: mapIdbyOldInternCyc.KeySet()
  21.             ];
  22.             
  23.              System.debug('oppListByOldCyc '+oppListByOldCyc);
  24.             
  25.             //Set<Opportunity> oppsToClone = new Set<Opportunity>();
  26.             List<Opportunity> oppsToClone = new List<Opportunity>();
  27.             
  28.             for(Id tmp : mapIdbyNewInternCyc.keySet()){                 
  29.                 for(Opportunity opp : oppListByOldCyc){
  30.                     Opportunity opps = new Opportunity();
  31.                     opps.Name = 'Clone Opportunity';
  32.                     opps.RecordTypeId = opp.RecordTypeId;
  33.                     opps.CloseDate = opp.CloseDate;
  34.                     opps.StageName = opp.StageName;
  35.                     opps.AccountId = opp.AccountId;
  36.                     opps.Internship_Cycle__c = tmp;
  37.                     oppsToClone.add(opps);
  38.                     
  39.                 }
  40.             }
  41.             
  42.             //List<Opportunity> op = new List<Opportunity>(oppsToClone);
  43.             insert oppsToClone;
  44.             
  45.             System.debug('Opportunity>>>'+oppsToClone);
  46.             
  47.             /*}catch (Exception e){
  48.             system.debug('Error '+e.getMessage() +' '+e.getLineNumber());
  49.         }*/
  50.         
  51.      } 
  52.  
  53. }
  1. @isTest
  2. public class alu_Internship_ControllerTest{
  3.     
  4.     Id OppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Internship Opportunity').getRecordTypeId();
  5.     
  6.     public static testMethod void testaluController(){
  7.         
  8.          Account testAccount = new Account();
  9.          testAccount.Name = 'Test Account' ;
  10.          insert testAccount;
  11.          
  12.          alu_Internship_Cycle__c ic = new alu_Internship_Cycle__c();
  13.          ic.Name = 'Test Cycle';
  14.          ic.Start_Date__c = System.Today();
  15.          ic.End_Date__c    = System.Today() + 60;
  16.          insert ic;
  17.          
  18.          Opportunity opp = new Opportunity();
  19.          opp.RecordTypeId = '0120Y000000QELh';
  20.          opp.Name = 'Test Opportunity';
  21.          opp.StageName = 'Under Discussion';
  22.          opp.CloseDate = System.Today();
  23.          opp.AccountId = testAccount.Id;
  24.          opp.Internship_Cycle__c = ic.Id;
  25.          opp.Number_of_Internships_Committed__c = 1;
  26.          opp.Opportunity_Countries__c = 'Algeria';
  27.          insert opp;
  28.          
  29.          PageReference pageRef = Page.alu_Internship_form;
  30.          Test.setCurrentPage(pageRef);
  31.            alu_Internship_Controller testIntCyc = new alu_Internship_Controller();
  32.          testIntCyc.doInsert();
  33.  
  34.                   
  35.     }
  36. }
  37. public class alu_Internship_Controller {
  38.     
  39.     Id OppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Internship Opportunity').getRecordTypeId();
  40.     public final static String STAGE_NAME_UD = 'Under Discussion';
  41.     
  42.     public Opportunity opps {get;set;}
  43.     public string str {get;set;}
  44.     public string counName {get;set;}
  45.     public String oppdes {get; set;}
  46.     public String names {get; set;}
  47.     public string cycleName { get; set;}
  48.     public Id Idc {get; set;}
  49.     public string cmpweb { get; set;}
  50.     public string oppcitiesofOper{get;set;}
  51.     public string oppPotPro{get;set;}
  52.     public List<string> couName { get; set;}
  53.     public List<String> listOfCompany {get; set;}
  54.     public Map<Id,String> mapIdStr {get; set;} 
  55.     public Id Ids {get; set;}
  56.     public Id opIds {get; set;}
  57.     public String acc {get; set;}
  58.     public Decimal noOfPosition {get;set;}
  59.     
  60.     public alu_Internship_Controller() {
  61.         opps = new Opportunity();
  62.         opps.RecordTypeId = OppRecordTypeId;
  63.         
  64.         mapIdStr = new Map<Id,String>();
  65.         listOfCompany = new List<String>();
  66.         for(Account a: [SELECT Id, Name From Account]) {
  67.             mapIdStr.put(a.Id, a.Name);
  68.             listOfCompany.add(a.name);
  69.         }
  70.     } 
  71.     public list<SelectOption> listCycleName {
  72.         get{
  73.             list<SelectOption> listSO = new list<SelectOption>();
  74.             listSO.add(new SelectOption('', 'Select Internship Cycle'));
  75.             for (alu_Internship_Cycle__c cyc : [select Id, Name from alu_Internship_Cycle__c]) {
  76.                 if(cyc != null) {
  77.                     listSO.add(new SelectOption(cyc.Id, cyc.Name));
  78.                 }
  79.             }
  80.             return listSO;
  81.         }
  82.        set;
  83.     }
  84.     public List<SelectOption> getCountries() {
  85.  
  86.         List<SelectOption> options = new List<SelectOption>();
  87.         Schema.DescribeFieldResult fieldResult = Opportunity.Opportunity_Countries__c.getDescribe();
  88.         List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();   
  89.         for( Schema.PicklistEntry f : ple) {
  90.             options.add(new SelectOption(f.getLabel(), f.getValue()));
  91.         }
  92.         return options;
  93.     }
  94.     public List<SelectOption> getStages() {
  95.  
  96.         List<SelectOption> options = new List<SelectOption>();
  97.         Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe();
  98.         List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
  99.         for(Schema.PicklistEntry f : ple){
  100.             options.add(new SelectOption(f.getLabel(), f.getValue()));
  101.         }
  102.         return options;
  103.     }
  104.     
  105.     // Logic for Save Button.
  106.     public PageReference doInsert() {
  107.        
  108.         // Storing Id and Acccount Name If acc contains same name.
  109.         Map<Id,String> mapString = new Map<Id,String>();    
  110.         for(Id tmp : mapIdStr.KeySet()) {
  111.             String name = mapIdStr.get(tmp);
  112.             if(acc.Contains(name)){
  113.                 mapString.put(tmp,acc);
  114.             }          
  115.         }
  116.         for(Id Accid: mapString.KeySet()){
  117.             Ids = Accid;
  118.         }
  119.         System.debug('Ids'+Ids);
  120.         
  121.         
  122.         // validation Logic Start
  123.         if (acc == ''){
  124.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select a Company Name'));
  125.         return null;
  126.         }
  127.         if (cmpweb == ''){
  128.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter an Company Website'));
  129.         return null;
  130.         }
  131.         if (cycleName == null){
  132.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter an Preffered Internship Cycle'));
  133.         return null;
  134.         }
  135.         if (noOfPosition == null){
  136.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select a Number of Position'));
  137.         return null;
  138.         }    
  139.              
  140.         // Iterating OpportunityId from List Of Opportunity
  141.         for(Opportunity opps : opportunitylists(Ids, cycleName)) {
  142.             opIds = opps.Id;
  143.         }
  144.         for(string s : couName) {
  145.             if(counName != null){
  146.                 counName= counName+';'+s;
  147.             }else{
  148.                 counName = s;
  149.             }            
  150.         }
  151.         if (counName == null){
  152.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select a Countries Operation'));
  153.         return null;
  154.         } 
  155.     
  156.         Account ac = new Account();        
  157.         if(opIds != null) {
  158.             Opportunity opp = new Opportunity();
  159.             opp.Id = opIds;
  160.             opp.Opportunity_Countries__c = '';
  161.             opp.Opportunity_Description__c = oppdes;
  162.             opp.AccountId = Ids;
  163.             opp.Internship_Cycle__c = cycleName;
  164.             opp.Number_of_Internships_Committed__c = noOfPosition;
  165.             opp.Opportunity_Countries__c = counName;
  166.             update opp;
  167.             system.debug('Opp Update'+ opp);
  168.             
  169.             ac.Id= opp.AccountId;
  170.             ac.Website = cmpweb;
  171.             update ac;
  172.             system.debug('ACC Update'+ ac);
  173.             
  174.         } else {
  175.             Opportunity opp = new Opportunity();
  176.             opp.RecordTypeId = OppRecordTypeId;
  177.             opp.name = '-UG Internship-';
  178.             opp.Opportunity_Description__c = oppdes;
  179.             opp.CloseDate = System.today();
  180.             opp.AccountId = Ids;
  181.             opp.StageName = STAGE_NAME_UD;
  182.             opp.Internship_Cycle__c = cycleName;
  183.             opp.Opportunity_Countries__c = counName;
  184.             opp.Number_of_Internships_Committed__c = noOfPosition;
  185.             insert opp;
  186.             system.debug('Opp Insert'+ opp);
  187.             
  188.             ac.Id= opp.AccountId;
  189.             ac.Website = cmpweb;
  190.             update ac; 
  191.             system.debug('ACC Update'+ ac);
  192.         }      
  193.         pagereference ref = new pagereference('/apex/alu_Internship_Thanks_Msg');
  194.         ref.setredirect(true);
  195.         return ref;
  196.     }  
  197.      
  198.     // getting list of Opportunity    
  199.     public List<Opportunity> opportunitylists (Id Ids, String cycleName) {
  200.         return [SELECT Id, AccountId, Internship_Cycle__c 
  201.                 FROM Opportunity 
  202.                 WHERE AccountId =:Ids 
  203.                 AND Internship_Cycle__c = : cycleName 
  204.                 AND Stagename=: STAGE_NAME_UD
  205.                 ];
  206.     }
  207. }
  208.  
  1. @isTest
  2. private class OpportunityMatchingHelperTest {
  3.     
  4.     private static testMethod void testCreateRecord() {
  5.         
  6.     Id conRecID = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('Student').getRecordTypeId(); 
  7.     Id oppRecID = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Opportunity').getRecordTypeId();  
  8.     
  9.         Test.startTest();
  10.         
  11.         Account acc = new Account(Name = 'test');
  12.         Insert acc;
  13.         
  14.         Contact con = new Contact(Lastname = 'test con',Email = 'test@gmail.com',AccountId = acc.Id,Academic_Standing__c = 'Good Standing',recordTypeId = conRecID);
  15.         Insert con;
  16.         
  17.         Opportunity opp = new Opportunity(AccountId = acc.Id,recordTypeId = oppRecID,Name = 'Demo',StageName = 'Demo',CloseDate = System.Today(),Key_Contact__c = con.Id);
  18.         Insert opp;
  19.         
  20.         alu_Opportunity_Matching__c aluOpp = new alu_Opportunity_Matching__c(Opportunity__c = opp.Id,Applicant_Student_Record__c = con.Id, Application_Status__c = 'Potential Candidate');
  21.         Insert aluOpp;
  22.         
  23.         Blob b = Blob.valueOf('Test Data'); 
  24.         
  25.         Attachment attachment = new Attachment(ParentId = opp.id,Name = 'Test Attachment for Parent',Body = b);  
  26.         Insert attachment;
  27.         
  28.         aluOpp.Application_Status__c = 'Pitched';
  29.         Update aluOpp;
  30.  
  31.         Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
  32.         efa.setFileName( attachment.Name);
  33.         efa.setBody(b); 
  34.         
  35.          List<Attachment> attList = new List<Attachment>();
  36.             for(Integer i=0;i<6;i++){
  37.              Attachment Attac =new Attachment();
  38.              Attac.Name='Unit Test Attachment';
  39.              Blob bodyBlob=Blob.valueOf('Unit Test Attachment Body');
  40.              Attac.body=bodyBlob;
  41.              Attac.parentId=opp.id;
  42.              attList.add(Attac);
  43.             }
  44.          insert attList;             
  45.     }        
  46. }
User-added image
I have written an trigger for update application object based on new created record, in update logic its working but I am getting error on Insert Logic.
Apex trigger AppLeadCreation caused an unexpected exception, contact your administrator: AppLeadCreation: execution of AfterInsert caused by: System.FinalException: Record is read-only: Trigger.AppLeadCreation: line 68, column 1
Please check the below code and suggest me what's wrong with this?
  1. trigger AppLeadCreation on alu_Application__c (after insert,before update){
  2.     
  3.     // SOQL QUERY FOR ITERATES
  4.     private static List<Lead> leadsList= new List<Lead>();
  5.     private static Set<String> appEmails = new Set<String>();
  6.   
  7.     
  8.     // MAP OF IDs AND EMAIL ADDRESS OF LEAD
  9.     private static  Map<String,Id> mapIdsWithLeadEmail = new Map<String,Id>();
  10.     
  11.     // MAP OF IDs AND EMAIL ADDRESS OF APPLICATION
  12.     Map<Id,String> mapIdsWithAppEmail = new Map<Id,String>();
  13.    
  14.     // MAP OF LEAD IDs AND APPLICATION ID
  15.     Map<Id,Id> mapAppIdsEmailIds = new Map<Id,Id>();
  16.     
  17.     Map<Id,Lead> mapAppIdwithLeads = new Map<Id,Lead>();
  18.     
  19.     Map<Id,Lead> leadsToCreate = new Map<Id,Lead>();
  20.     
  21.     Map<Id,Lead> leadtoUpdate = new Map<Id,Lead>();     
  22.     
  23.     Map<Id,alu_Application__c> apptoUpdate = new Map<Id,alu_Application__c>(); 
  24.    // to prevent the recursion    
  25.     public static boolean isRecursive=true;
  26.     System.debug('mapIdsWithLeadEmail'+mapIdsWithLeadEmail);
  27.     
  28.     for(alu_Application__c app : trigger.new){
  29.         if(String.isNotBlank(app.Email__c)){
  30.            mapIdsWithAppEmail.put(app.Id,app.Email__c);
  31.            appEmails.add(app.Email__c);
  32.          }
  33.     }
  34.     System.debug('mapIdsWithAppEmail'+mapIdsWithAppEmail);
  35.     try {
  36.            if(!mapIdsWithAppEmail.isEmpty() && isRecursive){
  37.                isRecursive = false;
  38.               // fetch leads information based on Application Email
  39.               leadsList =[SELECT Id, Email FROM Lead WHERE Email IN: appEmails];
  40.               if(!leadsList.isEmpty()){
  41.                  for(Lead le : leadsList){       
  42.                    mapIdsWithLeadEmail.put(le.email, le.Id);
  43.               }
  44.              } 
  45.             
  46.             for(Id tmp : mapIdsWithAppEmail.KeySet()){
  47.                 String appEmail = mapIdsWithAppEmail.get(tmp);
  48.                if(mapIdsWithLeadEmail.ContainsKey(appEmail)){ 
  49.                    mapAppIdsEmailIds.put(tmp,mapIdsWithLeadEmail.get(appEmail));
  50.                }else{
  51.                     leadsToCreate.put(tmp,leadInfo(trigger.newMap.get(tmp),'insert',null));
  52.                }
  53.               }
  54.             }
  55.         System.debug('mapAppIdsEmailIds'+mapAppIdsEmailIds);
  56.         System.debug('leadsToCreate'+leadsToCreate);
  57.         
  58.         if(!mapAppIdsEmailIds.isEmpty() || !leadsToCreate.isEmpty()){
  59.             //insert the new leads for unmathced application EMAIL
  60.             Database.insert(leadsToCreate.values());
  61.             
  62.             for(alu_Application__c app : trigger.new){
  63.                 if(mapAppIdsEmailIds.ContainsKey(app.Id)){
  64.                     app.Lead__c = mapAppIdsEmailIds.get(app.Id);
  65.                     leadtoUpdate.put(app.Id, leadInfo(app,'update',app.Lead__c));
  66.                 }               
  67.                 else if(leadsToCreate.containsKey(app.Id)){
  68.                     app.Lead__c = leadsToCreate.get(app.Id).Id;
  69.                 }
  70.                 if(Trigger.isAfter && Trigger.isInsert && app.Lead__c != NULL){
  71.                     apptoUpdate.put(app.Id,app);
  72.                 }
  73.             }
  74.             if(!leadtoUpdate.isEmpty()){
  75.                 update leadtoUpdate.values();
  76.             }
  77.             if(!apptoUpdate.isEmpty()){
  78.                 update apptoUpdate.values();
  79.             }
  80.          }     
  81.         }Catch(Exception e){
  82.         System.debug('ERROR:' + e.getMessage());
  83.         System.debug('ERROR:' + e.getLineNumber());
  84.       }
  85.         
  86.      private static Lead leadInfo(alu_Application__c app, String eventType, Id LeadId){
  87.          Lead leadtoSend = new Lead();
  88.          if(eventType.equals('update')){
  89.              leadtoSend.Id = LeadId;
  90.          }
  91.          leadtoSend.FirstName = app.First_Name__c;
  92.          leadtoSend.LastName = app.Last_Name__c;
  93.          leadtoSend.Email = app.Email__c;
  94.          leadtoSend.Campus_Preference__c = app.Campus_Preference__c; 
  95.          leadtoSend.Company = app.First_Parent_Company__c;
  96.         
  97.          
  98.         return leadtoSend;
  99.      }
  100.     
  101. }
trigger AppLeadCreation on alu_Application__c (before insert, before update) {
    
    // SOQL QUERY FOR ITERATES
    Map<Id,Lead> mapLeads = new Map<Id,Lead>([SELECT Id, Email FROM Lead]);
    System.debug('mapLeads'+mapLeads);
    
    // MAP OF IDs AND EMAIL ADDRESS OF LEAD
    Map<String,Id> mapIdsWithLeadEmail = new Map<String,Id>();
    
    // MAP OF IDs AND EMAIL ADDRESS OF APPLICATION
    Map<String,Id> mapIdsWithAppEmail = new Map<String,Id>();
    
    // MAP OF LEAD IDs AND APPLICATION ID
    Map<Id,Id> mapAppIdsEmailIds = new Map<Id,Id>();
        
    for(Lead le : mapLeads.values()){       
        mapIdsWithLeadEmail.put(le.email, le.Id);
    }
    System.debug('mapIdsWithLeadEmail'+mapIdsWithLeadEmail);
    
    for(alu_Application__c app : trigger.new){
         mapIdsWithAppEmail.put(app.Email__c, app.Id);
    }
    System.debug('mapIdsWithAppEmail'+mapIdsWithAppEmail);
    try{
   
        for(Id tmp : mapIdsWithAppEmail.Values()){
           if(mapIdsWithLeadEmail.ContainsKey(mapIdsWithAppEmail.get(tmp))){ 
               mapAppIdsEmailIds.put(tmp,mapIdsWithLeadEmail.get(tmp));       //Here I getting only ID of Application record not for Lead
            } 
        }
        System.debug('mapAppIdsEmailIds'+mapAppIdsEmailIds); 
     }Catch(Exception e){
        System.debug('ERROR:' + e.getMessage());
        System.debug('ERROR:' + e.getLineNumber());
    }
    
}
I want to create a new record and want to rediret on that page, Once the picklist value will change to Demo.

Thanks,
Sumit
        for(alu_Opportunity_Matching__c opp :OppMapByIDs.values()){           
            if(opp.Applicant_Student_Record__c != null){
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setTargetObjectId(opp.Applicant_Student_Record__c);
                singleMail.setTemplateId(et.Id);
                singleMail.setWhatId(opp.Id);
                singleMail.setSaveAsActivity(false);
                singleMail.setReplyTo('mycareer@gmail.com');
                   singleMail.setSenderDisplayName('Career Development');
                singleMail.setFileAttachments(fileAttachments);
                emails.add(singleMail); 
            }
        }  
        Messaging.sendEmail(emails);
Like I am updating a single record than its sending a specific attachment for that contact record, but when I updating data by data loader it's attaching all attachment from all contacts and sending on email. 

please help me on this,

thanks
public with sharing class OpportunityMatchingHelper {
 
    public static List<alu_Opportunity_Matching__c> sendEmail(List<alu_Opportunity_Matching__c> oppList) { 
        Map<Id,alu_Opportunity_Matching__c> OppMapByIDs = new Map<Id,alu_Opportunity_Matching__c>();
        List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
        List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
        
        EmailTemplate et=[Select Id,Subject,HtmlValue,Body FROM EmailTemplate WHERE Name=:'Pitched'];          
        for(alu_Opportunity_Matching__c opMap : oppList){
            if(opMap.Application_Status__c == 'Pitched'){
                OppMapByIDs.put(opMap.Applicant_Student_Record__c, opMap);    
            }        
        }
        for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :OppMapByIDs.keySet()])
        {
           Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
           efa.setFileName(a.Name);
           efa.setBody(a.Body);
           fileAttachments.add(efa);
        }
        
        for(alu_Opportunity_Matching__c opp :OppMapByIDs.values()){           
            if(opp.Applicant_Student_Record__c != null){
                Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
                singleMail.setTargetObjectId(opp.Applicant_Student_Record__c);
                singleMail.setTemplateId(et.Id);
                singleMail.setWhatId(opp.Id);
                singleMail.setSaveAsActivity(false);
                singleMail.setReplyTo('mycareer@alueducation.com');
                   singleMail.setSenderDisplayName('ALU Career Development');
                singleMail.setFileAttachments(fileAttachments);
                emails.add(singleMail); 
            }
        }  
        Messaging.sendEmail(emails);
        return null;
    }
}
 
Hi All, 
I create apex class for sending email template with attachment. When I uploading data through data loader then I am getting the issue.
Like I am updating a single record than its sending a specific attachment for that contact record, but when I updating data by data loader it's attaching all attachment from all contacts and sending on email. 

please help me on this,

thanks
  1. public with sharing class OpportunityMatchingHelper {
  2.  
  3.     public static List<alu_Opportunity_Matching__c> sendEmail(List<alu_Opportunity_Matching__c> oppList) { 
  4.         Map<Id,alu_Opportunity_Matching__c> OppMapByIDs = new Map<Id,alu_Opportunity_Matching__c>();
  5.         List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
  6.         List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>();
  7.         
  8.         EmailTemplate et=[Select Id,Subject,HtmlValue,Body FROM EmailTemplate WHERE Name=:'Pitched'];          
  9.         for(alu_Opportunity_Matching__c opMap : oppList){
  10.             if(opMap.Application_Status__c == 'Pitched'){
  11.                 OppMapByIDs.put(opMap.Applicant_Student_Record__c, opMap);    
  12.             }        
  13.         }
  14.         for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :OppMapByIDs.keySet()])
  15.         {
  16.            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
  17.            efa.setFileName(a.Name);
  18.            efa.setBody(a.Body);
  19.            fileAttachments.add(efa);
  20.         }
  21.         
  22.         for(alu_Opportunity_Matching__c opp :OppMapByIDs.values()){           
  23.             if(opp.Applicant_Student_Record__c != null){
  24.                 Messaging.SingleEmailMessage singleMail = new Messaging.SingleEmailMessage();
  25.                 singleMail.setTargetObjectId(opp.Applicant_Student_Record__c);
  26.                 singleMail.setTemplateId(et.Id);
  27.                 singleMail.setWhatId(opp.Id);
  28.                 singleMail.setSaveAsActivity(false);
  29.                 singleMail.setReplyTo('mycareer@alueducation.com');
  30.                    singleMail.setSenderDisplayName('ALU Career Development');
  31.                 singleMail.setFileAttachments(fileAttachments);
  32.                 emails.add(singleMail); 
  33.             }
  34.         }  
  35.         Messaging.sendEmail(emails);
  36.         return null;
  37.     }
  38. }
  1. public class ControllerFeedback {
  2.     public alu_Opportunity_Matching__c objs {get;set;}
  3.     public void init() {
  4.         Id ids = ApexPages.currentPage().getParameters().get('id');    
  5.         system.debug('Id'+ids);
  6.         alu_Opportunity_Matching__c obj = [select id, Applicant_Student_Record__r.Name, Application_Status__c,Opportunity__r.Name FROM alu_Opportunity_Matching__c WHERE id = :ids];        
  7.         objs = obj;
  8.         system.debug('name'+objs);
  9.         obj.Application_Status__c = 'Opted-out';
  10.         Update obj; 
  11.         return;        
  12.     }
  13.     
 
  1. }
  2. @isTest
  3. public class ControllerFeedbackTests {
  4.     
  5.     static testMethod void test_ControllerFeedback() {
  6.         
  7.     test.startTest();
  8.     
  9.     account acc = new account();
  10.     acc.Name = 'test';
  11.     insert acc;
  12.     
  13.     Contact con = new Contact();
  14.     con.Lastname = 'test con';
  15.     con.Email = 'test@gmail.com';
  16.     con.AccountId = acc.Id;
  17.     insert con;
  18.     
  19.     Opportunity opp = new Opportunity();
  20.     opp.AccountId = acc.Id;
  21.     opp.Name = 'Demo';
  22.     opp.StageName = 'Demo';
  23.     opp.CloseDate = System.Today();
  24.     opp.Key_Contact__c = con.Id;
  25.     insert opp;
  26.  
  27.     alu_Opportunity_Matching__c aluOpp = new alu_Opportunity_Matching__c();
  28.     aluOpp.Applicant_Student_Record__c = opp.Key_Contact__c;
  29.     aluOpp.Opportunity__c = opp.Id;
  30.     aluOpp.Application_Status__c = 'none';
  31.  
  32.     insert aluOpp; 
  33.     
  34.     PageReference testPage = new pagereference('/apex/feedback');
  35.     ApexPages.currentPage().getParameters().put( 'id', aluOpp.id );
  36.     
  37.     ControllerFeedback cf = new ControllerFeedback();
  38.     cf.init(); 
  39.     
  40.     test.stopTest();
  41.     }
  42.     
  43. }
Hi Members,
I have created a vf page and controller where I used action method, Now I want to display some data from controller but I am not able to retrieve. if I am creating constructor then Void method is not working.
Getting Error "Unknown property 'ControllerFeedback.obj'"
Below are the code: 
  1. <apex:page controller="ControllerFeedback">
  2.     <apex:form >
  3.      <apex:actionFunction name="doCallout" action="{!init}" rerender="none"/>   
  4.       </apex:form>
  5.     
  6.     <script>
  7.         window.onload=function()
  8.         {
  9.             doCallout();
  10.         }
  11.     </script> 
  12.     <p><center><b>You have Successfully update Opt Out.</b></center></p>  
  13.     <apex:outputPanel>
  14.         <apex:repeat value="{!obj}" var="a">
  15.              <p>{!a.Name}</p>
  16.         </apex:repeat>    
  17.     </apex:outputPanel>
  18. </apex:page>
 
  1. public class ControllerFeedback {
  2.     private final alu_Opportunity_Matching__c obj;
  3.     public void init() {
  4.         Id ids = ApexPages.currentPage().getParameters().get('id');    
  5.         system.debug('Id'+ids);
  6.         alu_Opportunity_Matching__c obj = [select id, Name,Application_Status__c FROM alu_Opportunity_Matching__c WHERE id = :ids];        
  7.         obj.Application_Status__c = 'Withdrawn';
  8.         Update obj; 
  9.         return;        
  10.     }
  11. }
Thanks
Sumit,
Hi,
I want to update one field,once the vf page will be loaded.
Or 
Is there any way to update a field once the user click sites link.

Thanks
I have created one custom site link for update field.

Now I want to add time session on it. 
Like, if the user did not click this link before 24 hours the session will expire and will be not able to update the record by the same link.

How can I do that?

this is my VF page which I am using under sites.​
  1. <apex:page standardController="Bank__c" >
  2. <apex:form >
  3.     <apex:pageBlock >
  4.         <apex:pageBlockSection >
  5.             <apex:inputField value="{!Bank__c.Response__c}"/>
  6.             <apex:inputField value="{!Bank__c.Name}"/>
  7.         </apex:pageBlockSection>
  8.         <apeX:pageBlockButtons >
  9.             <apex:commandButton value="Save" action="{!Save}"/>
  10.         </apeX:pageBlockButtons>
  11.     </apex:pageBlock>
  12.     
  13. </apex:form>
  14. </apex:page>
Thanks & Regards 
Sumit
Dear Test,
Please "click me" to update your details.

Once the user clicked on click me from his email, then one salesforce field will be updated.
How can I proceed . 
  1. trigger EventTriggers on Event (after insert, after update) {
  2.     EventHandler.AddCampaginMember(trigger.new);
  3. }
Hi,
I am getting coverage issue while deploying updated trigger through sandbox.

In production I have 80% coverage and I have also checked not test class getting failed but when I deploying any trigger or class I am getting this Error Msg.

Code Coverage Failure
The following triggers have 0% code coverage. Each trigger must have at least 1% code coverage.
EventTriggers


Please Help me on this.
I am using this validation formula but it's not working

OR(LEN(URL__c) = 1,NOT(CONTAINS("www.",URL__c)))
This Code but I think this is not correct
  1. global class BatchOpportunitys implements Database.Batchable<SObject>, Database.Stateful{
  2.              
  3.     
  4.     List<Opportunity> listRecords = new List<Opportunity>();
  5.    
  6.     global Database.QueryLocator start(Database.BatchableContext BC)
  7.     {
  8.         String query = 'Select Id, Name, CloseDate,StageName From Opportunity';
  9.         return Database.getQueryLocator(query);
  10.     }
  11.      
  12.     global void execute(Database.BatchableContext BC, List<SObject> scope){
  13.     
  14.         for(Opportunity obj : (Opportunity[]) scope){
  15.             
  16.             if(obj.StageName == 'Qualification'){
  17.                 obj.CloseDate = date.today();
  18.                 obj.StageName = 'Value Proposition';
  19.                 obj.account.ownerId = obj.ownerId;
  20.                 obj.account.Status__c = 'Lost';   
  21.                 listRecords.add(obj);
  22.             }
  23.             
  24.          }
  25.     
  26.     }
  27.     
  28.     global void finish(Database.BatchableContext BC){
  29.         system.debug('list size  :: '+listRecords.size());
  30.         if(!listRecords.isEmpty())
  31.             {
  32.               update listRecords;
  33.             }
  34.     }
  35. }

 
Line no 14 I am getting this error. "Type cannot be constructed: String" Please help me on this.
  1.    public String type_Z {get;set;} 
  2.     public List<String> authcookies {get;set;} 
  3.  
  4.     public JsonStringsss(JSONParser parser) {
  5.         while (parser.nextToken() != JSONToken.END_OBJECT) {
  6.             if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  7.                 String text = parser.getText();
  8.                 if (parser.nextToken() != JSONToken.VALUE_NULL) {
  9.                     if (text == 'type') {
  10.                         type_Z = parser.getText();
  11.                     } else if (text == 'auth-cookies') {
  12.                         authcookies = new List<String>();
  13.                         while (parser.nextToken() != JSONToken.END_ARRAY) {
  14.                             authcookies.add(new String(parser));
  15.                         }
  16.                     } else {
  17.                         System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
  18.                         consumeObject(parser);
  19.                     }
  20.                 }
  21.             }
  22.         }
  23.     }
public with sharing class contollertest {

    Public id Current_le_Id;
    public Boolean isEdit { set; get;}
    public List<Question__c> lstQuestion {set;get;}
    public contollertest (ApexPages.StandardController controller) {
        Current_le_Id = controller.getRecord().id;
        isEdit = false;
        lstQuestion = New List<Question__c>();
        for(Lead le:[select id,name,(select id,Name,Email__c from Questions__r) from lead where id=:Current_le_Id]){
           for(Question__c con:le.Question__c)
               lstQuestion.add(con);
        }
    }
    public void editProcess(){
        isEdit = true;
    }
    public  void save(){
        
        if(lstQuestion.size() > 0){
            upsert lstQuestion;
            lstQuestion.clear();
        }
        
        for(Lead le:[select id,name,(select id,Name,Email__c from Questions__r) from lead where id=:Current_le_Id]){
           for(Question__c con:le.Question__c)
               lstQuestion.add(con);
        }
        isEdit = false;
    }
    public void addQuestion(){
        lstQuestion.add(new Question(leadId = Current_le_Id));
        isEdit = true;
    }
}
<!--Page-->
<apex:page standardController="Account" extensions="contrllr">
  <apex:form >
    <apex:pageblock id="pgb">
    <apex:pageBlockButtons >
        <apex:commandButton value="edit" action="{!editProcess}" rendered="{!Not(isEdit)}" reRender="pgb"/>
        <apex:commandButton value="save" action="{!save}" rendered="{!isEdit}" reRender="pgb"/>        
        </apex:pageBlockButtons>
       <apex:pageBlockTable value="{!lstQuestion}" var="val" rendered="{!Not(isEdit)}">
         <apex:column value="{!val.Name}"/>
         <apex:column value="{!val.Email__c}"/>
       </apex:pageBlockTable> 
       <apex:outputPanel rendered="{!Not(isEdit)}">
           <apex:commandButton action="{!addQuestion}" value="Add Contact" reRender="pgb"/>
       </apex:outputPanel>
        <apex:pageBlockTable value="{!lstQuestion}" var="val" rendered="{!(isEdit)}">
         <apex:column headerValue="FirstName">
             <apex:inputField value="{!val.Name}"/>
         </apex:column>
          <apex:column headerValue="Email">
             <apex:inputField value="{!val.Email__c}"/>
         </apex:column>
         <apex:column >
             <apex:inputField value="{!val.Email__c}"/>
         </apex:column>
       </apex:pageBlockTable> 
    </apex:pageblock>
  </apex:form>
</apex:page>
I want to add Lead and Question__c.this object on this code, i tried but getting error

public with sharing class contrllr {

    Public id Current_Acc_Id;
    public Boolean isEdit { set; get;}
    public List<Contact> lstContact {set;get;}
    public contrllr (ApexPages.StandardController controller) {
        Current_Acc_Id = controller.getRecord().id;
        isEdit = false;
        lstContact = New List<Contact>(); 
        for(Account acc:[select id,name,(select lastName,firstName,name,id,email from contacts) from account where id=:Current_Acc_Id]){
           for(contact con:acc.contacts)
               lstContact.add(con); 
        }
    }
    public void editProcess(){
        isEdit = true;
    }
    public  void save(){
        
        if(lstContact.size() > 0){
            upsert lstContact;
            lstContact.clear();
        }
        
        for(Account acc:[select id,name,(select lastName,firstName,name,id,email from contacts) from account where id=:Current_Acc_Id]){
           for(contact con:acc.contacts)
               lstContact.add(con); 
        }
        isEdit = false;
    } 
    public void addContact(){
        lstContact.add(new Contact(AccountId = Current_Acc_Id));
        isEdit = true;
    }
}
  1. @isTest
  2. public class alu_Internship_ControllerTest{
  3.     
  4.     Id OppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Internship Opportunity').getRecordTypeId();
  5.     
  6.     public static testMethod void testaluController(){
  7.         
  8.          Account testAccount = new Account();
  9.          testAccount.Name = 'Test Account' ;
  10.          insert testAccount;
  11.          
  12.          alu_Internship_Cycle__c ic = new alu_Internship_Cycle__c();
  13.          ic.Name = 'Test Cycle';
  14.          ic.Start_Date__c = System.Today();
  15.          ic.End_Date__c    = System.Today() + 60;
  16.          insert ic;
  17.          
  18.          Opportunity opp = new Opportunity();
  19.          opp.RecordTypeId = '0120Y000000QELh';
  20.          opp.Name = 'Test Opportunity';
  21.          opp.StageName = 'Under Discussion';
  22.          opp.CloseDate = System.Today();
  23.          opp.AccountId = testAccount.Id;
  24.          opp.Internship_Cycle__c = ic.Id;
  25.          opp.Number_of_Internships_Committed__c = 1;
  26.          opp.Opportunity_Countries__c = 'Algeria';
  27.          insert opp;
  28.          
  29.          PageReference pageRef = Page.alu_Internship_form;
  30.          Test.setCurrentPage(pageRef);
  31.            alu_Internship_Controller testIntCyc = new alu_Internship_Controller();
  32.          testIntCyc.doInsert();
  33.  
  34.                   
  35.     }
  36. }
  37. public class alu_Internship_Controller {
  38.     
  39.     Id OppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Internship Opportunity').getRecordTypeId();
  40.     public final static String STAGE_NAME_UD = 'Under Discussion';
  41.     
  42.     public Opportunity opps {get;set;}
  43.     public string str {get;set;}
  44.     public string counName {get;set;}
  45.     public String oppdes {get; set;}
  46.     public String names {get; set;}
  47.     public string cycleName { get; set;}
  48.     public Id Idc {get; set;}
  49.     public string cmpweb { get; set;}
  50.     public string oppcitiesofOper{get;set;}
  51.     public string oppPotPro{get;set;}
  52.     public List<string> couName { get; set;}
  53.     public List<String> listOfCompany {get; set;}
  54.     public Map<Id,String> mapIdStr {get; set;} 
  55.     public Id Ids {get; set;}
  56.     public Id opIds {get; set;}
  57.     public String acc {get; set;}
  58.     public Decimal noOfPosition {get;set;}
  59.     
  60.     public alu_Internship_Controller() {
  61.         opps = new Opportunity();
  62.         opps.RecordTypeId = OppRecordTypeId;
  63.         
  64.         mapIdStr = new Map<Id,String>();
  65.         listOfCompany = new List<String>();
  66.         for(Account a: [SELECT Id, Name From Account]) {
  67.             mapIdStr.put(a.Id, a.Name);
  68.             listOfCompany.add(a.name);
  69.         }
  70.     } 
  71.     public list<SelectOption> listCycleName {
  72.         get{
  73.             list<SelectOption> listSO = new list<SelectOption>();
  74.             listSO.add(new SelectOption('', 'Select Internship Cycle'));
  75.             for (alu_Internship_Cycle__c cyc : [select Id, Name from alu_Internship_Cycle__c]) {
  76.                 if(cyc != null) {
  77.                     listSO.add(new SelectOption(cyc.Id, cyc.Name));
  78.                 }
  79.             }
  80.             return listSO;
  81.         }
  82.        set;
  83.     }
  84.     public List<SelectOption> getCountries() {
  85.  
  86.         List<SelectOption> options = new List<SelectOption>();
  87.         Schema.DescribeFieldResult fieldResult = Opportunity.Opportunity_Countries__c.getDescribe();
  88.         List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();   
  89.         for( Schema.PicklistEntry f : ple) {
  90.             options.add(new SelectOption(f.getLabel(), f.getValue()));
  91.         }
  92.         return options;
  93.     }
  94.     public List<SelectOption> getStages() {
  95.  
  96.         List<SelectOption> options = new List<SelectOption>();
  97.         Schema.DescribeFieldResult fieldResult = Opportunity.StageName.getDescribe();
  98.         List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
  99.         for(Schema.PicklistEntry f : ple){
  100.             options.add(new SelectOption(f.getLabel(), f.getValue()));
  101.         }
  102.         return options;
  103.     }
  104.     
  105.     // Logic for Save Button.
  106.     public PageReference doInsert() {
  107.        
  108.         // Storing Id and Acccount Name If acc contains same name.
  109.         Map<Id,String> mapString = new Map<Id,String>();    
  110.         for(Id tmp : mapIdStr.KeySet()) {
  111.             String name = mapIdStr.get(tmp);
  112.             if(acc.Contains(name)){
  113.                 mapString.put(tmp,acc);
  114.             }          
  115.         }
  116.         for(Id Accid: mapString.KeySet()){
  117.             Ids = Accid;
  118.         }
  119.         System.debug('Ids'+Ids);
  120.         
  121.         
  122.         // validation Logic Start
  123.         if (acc == ''){
  124.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select a Company Name'));
  125.         return null;
  126.         }
  127.         if (cmpweb == ''){
  128.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter an Company Website'));
  129.         return null;
  130.         }
  131.         if (cycleName == null){
  132.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter an Preffered Internship Cycle'));
  133.         return null;
  134.         }
  135.         if (noOfPosition == null){
  136.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select a Number of Position'));
  137.         return null;
  138.         }    
  139.              
  140.         // Iterating OpportunityId from List Of Opportunity
  141.         for(Opportunity opps : opportunitylists(Ids, cycleName)) {
  142.             opIds = opps.Id;
  143.         }
  144.         for(string s : couName) {
  145.             if(counName != null){
  146.                 counName= counName+';'+s;
  147.             }else{
  148.                 counName = s;
  149.             }            
  150.         }
  151.         if (counName == null){
  152.         ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select a Countries Operation'));
  153.         return null;
  154.         } 
  155.     
  156.         Account ac = new Account();        
  157.         if(opIds != null) {
  158.             Opportunity opp = new Opportunity();
  159.             opp.Id = opIds;
  160.             opp.Opportunity_Countries__c = '';
  161.             opp.Opportunity_Description__c = oppdes;
  162.             opp.AccountId = Ids;
  163.             opp.Internship_Cycle__c = cycleName;
  164.             opp.Number_of_Internships_Committed__c = noOfPosition;
  165.             opp.Opportunity_Countries__c = counName;
  166.             update opp;
  167.             system.debug('Opp Update'+ opp);
  168.             
  169.             ac.Id= opp.AccountId;
  170.             ac.Website = cmpweb;
  171.             update ac;
  172.             system.debug('ACC Update'+ ac);
  173.             
  174.         } else {
  175.             Opportunity opp = new Opportunity();
  176.             opp.RecordTypeId = OppRecordTypeId;
  177.             opp.name = '-UG Internship-';
  178.             opp.Opportunity_Description__c = oppdes;
  179.             opp.CloseDate = System.today();
  180.             opp.AccountId = Ids;
  181.             opp.StageName = STAGE_NAME_UD;
  182.             opp.Internship_Cycle__c = cycleName;
  183.             opp.Opportunity_Countries__c = counName;
  184.             opp.Number_of_Internships_Committed__c = noOfPosition;
  185.             insert opp;
  186.             system.debug('Opp Insert'+ opp);
  187.             
  188.             ac.Id= opp.AccountId;
  189.             ac.Website = cmpweb;
  190.             update ac; 
  191.             system.debug('ACC Update'+ ac);
  192.         }      
  193.         pagereference ref = new pagereference('/apex/alu_Internship_Thanks_Msg');
  194.         ref.setredirect(true);
  195.         return ref;
  196.     }  
  197.      
  198.     // getting list of Opportunity    
  199.     public List<Opportunity> opportunitylists (Id Ids, String cycleName) {
  200.         return [SELECT Id, AccountId, Internship_Cycle__c 
  201.                 FROM Opportunity 
  202.                 WHERE AccountId =:Ids 
  203.                 AND Internship_Cycle__c = : cycleName 
  204.                 AND Stagename=: STAGE_NAME_UD
  205.                 ];
  206.     }
  207. }
  208.  
I want to create a new record and want to rediret on that page, Once the picklist value will change to Demo.

Thanks,
Sumit
Hi,
I want to update one field,once the vf page will be loaded.
Or 
Is there any way to update a field once the user click sites link.

Thanks
Dear Test,
Please "click me" to update your details.

Once the user clicked on click me from his email, then one salesforce field will be updated.
How can I proceed . 
  1. trigger EventTriggers on Event (after insert, after update) {
  2.     EventHandler.AddCampaginMember(trigger.new);
  3. }
I am using this validation formula but it's not working

OR(LEN(URL__c) = 1,NOT(CONTAINS("www.",URL__c)))
This Code but I think this is not correct
  1. global class BatchOpportunitys implements Database.Batchable<SObject>, Database.Stateful{
  2.              
  3.     
  4.     List<Opportunity> listRecords = new List<Opportunity>();
  5.    
  6.     global Database.QueryLocator start(Database.BatchableContext BC)
  7.     {
  8.         String query = 'Select Id, Name, CloseDate,StageName From Opportunity';
  9.         return Database.getQueryLocator(query);
  10.     }
  11.      
  12.     global void execute(Database.BatchableContext BC, List<SObject> scope){
  13.     
  14.         for(Opportunity obj : (Opportunity[]) scope){
  15.             
  16.             if(obj.StageName == 'Qualification'){
  17.                 obj.CloseDate = date.today();
  18.                 obj.StageName = 'Value Proposition';
  19.                 obj.account.ownerId = obj.ownerId;
  20.                 obj.account.Status__c = 'Lost';   
  21.                 listRecords.add(obj);
  22.             }
  23.             
  24.          }
  25.     
  26.     }
  27.     
  28.     global void finish(Database.BatchableContext BC){
  29.         system.debug('list size  :: '+listRecords.size());
  30.         if(!listRecords.isEmpty())
  31.             {
  32.               update listRecords;
  33.             }
  34.     }
  35. }

 
This My Code
  1. global class BatchOpportunitys implements Database.Batchable <sObject>{
  2.     
  3.     Id oppRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('New Rec Type').getRecordTypeId(); 
  4.     date dt4 = system.today();  
  5.      
  6.     global Database.QueryLocator start(Database.BatchableContext BC){
  7.         
  8.         
  9.         String query = 'SELECT Id,StageName FROM Opportunity RecordTypeId =:oppRecordTypeId AND StageName : Prospecting';
  10.         return Database.getQueryLocator(query);
  11.         
  12.     }
  13.     global void execute(Database.BatchableContext BC, List<Opportunity> scope){
  14.         
  15.         for(Opportunity opps : scope)
  16.          {   
  17.              System.debug('opps');
  18.              opps.StageName = 'Qualification';
  19.             opps.CloseDate = dt4;
  20.              opps.account.ownerId = opps.ownerId;
  21.              opps.account.Status__c = 'Lost';         
  22.          }
  23.          update scope;
  24.          System.debug('Record'+scope); 
  25.     }
  26.                
  27.             
  28.     global void finish(Database.BatchableContext BC){
  29.             
  30.     }
  31. }
Currently Logic is If a Account Contains two Opportunity if 1.Opportunity Stage is "Closed Won" and If I am Updating 2 Opportunity Stage = "Closed Lost" then it will Update Account Status = Customer. 

I want add One more Logic Like If Opportunity Stage = Closed Lost then Account Status should Be Lost. In the below Code. How to I Implement 

public static void AfterListUpdateHandler(List<Opportunity> newOpps){
        Set<Id> accIds = new Set<Id>();
        Set<Account> acclists = new Set<Account>();
            for(Opportunity opp : newOpps){
                if(opp.StageName == STAGE_CLOSED_LOST){
                    accIds.add(opp.AccountId);
                }             
            }
        System.debug('OppListStage1 ::>'+accIds);
        Opportunity [] OppListStage  = [SELECT Id,StageName,AccountId FROM Opportunity WHERE AccountId IN: accIds AND StageName =: STAGE_CLOSED_WON];
        System.debug('OppListStage2 ::>'+OppListStage);
        
            if(OppListStage.size()>0){
                for(Opportunity op : OppListStage){
                    Account acc = new Account();
                    acc.Id = op.AccountId;
                    acc.Account_Status__c = STATUS_CHURNED_CUST;
                    acclists.add(acc);              
                }
                if(checkRecursive.runOnce()){
                    update new List<Account>(acclists);
                    System.debug('opp1 ::>acclists'+acclists);
                }
                 
            }    
        }
Hi, I have written helper class for updating opportunity. if Event Status = 'Cancelled' then I am updating opportunity Stage Field else if Event Type = 'Consultation'.  then I updating Opportunity Date field. I am trying to update both logic if both matching matched.

This the class I have written.
  1. public class EventHandler{
  2.     
  3.     public static void OpportunityStageUpdateBaseOnEventStatus (List<Event> evnList){
  4.         Boolean condition1=false;
  5.         Boolean condition2=false;
  6.         Map<Id,Event> mapID = new Map<Id,Event>();
  7.         Set<Opportunity> OppSet = new Set<Opportunity>();
  8.         for(Event evn: evnList){
  9.             mapID.put(evn.Id,evn);
  10.         }
  11.         System.debug('mapID'+mapID);
  12.         for(Event evn: mapID.values()){
  13.             if(evn.Type__c == 'Consultation'){
  14.                 System.debug('1');
  15.                 condition1=true;
  16.                 Opportunity opp = new Opportunity();
  17.                 opp.Id = evn.WhatId;
  18.                 Opp.Demo_Date_Time__c = evn.StartDateTime;
  19.                 OppSet.add(opp);                
  20.             }else if(evn.Status__c == 'cancelled'){
  21.                 System.debug('2');
  22.                 condition2=true;
  23.                 Opportunity opp = new Opportunity();
  24.                 opp.Id = evn.WhatId;
  25.                 Opp.StageName = 'Closed Lost';
  26.                 OppSet.add(opp);
  27.             }else if(condition1 ==true && condition2 ==true){
  28.                 System.debug('3');
  29.                 Opportunity opp = new Opportunity();
  30.                 opp.Id = evn.WhatId;
  31.                 Opp.Demo_Date_Time__c = evn.StartDateTime;
  32.                 Opp.StageName = 'Closed Lost';
  33.                 OppSet.add(opp);
  34.             }         
  35.         }
  36.         
  37.         if(OppSet.Size()>0){
  38.             System.debug('SIZE >>'+OppSet.Size());
  39.             update new List<Opportunity>(OppSet);
  40.             System.debug('SIZE >>'+OppSet);
  41.         }
  42.         
  43.                 
  44.     }
  45.     
  46. }
  1. trigger oppTr on Opportunity (after update,after insert){
  2.         
  3.     Map<Id,Opportunity> OppStage = new Map<Id,Opportunity>();
  4.     List<Account> AccList = new List<Account>();
  5.     
  6.     for(Opportunity opp : trigger.new){        
  7.         if(opp.StageName == 'Closed Lost' && trigger.oldMap.get(opp.Id).StageName == 'Closed Won'){
  8.            OppStage.put(opp.AccountId, opp);
  9.         }
  10.     }
  11.     System.debug('OppStage'+OppStage);
  12.    try {            
  13.    if(OppStage.size()>0){
  14.        System.debug('OppStage'+OppStage.size());
  15.         for(Opportunity opp2 : OppStage.values()){
  16.            System.debug('opp2'+opp2);
  17.            Account acc = new Account();
  18.            acc.Id = opp2.AccountId;
  19.            acc.Status__c = 'Lost';
  20.            AccList.add(acc);
  21.            System.debug('AccList'+acc.Status__c);
  22.         } 
  23.        update AccList;
  24.        System.debug('AccList'+AccList);
  25.     } 
  26.    } catch (System.NullPointerException e){
  27.      String s;
  28.         s.toLowerCase();
  29.    }   
  30.  
  31. }
Line no 14 I am getting this error. "Type cannot be constructed: String" Please help me on this.
  1.    public String type_Z {get;set;} 
  2.     public List<String> authcookies {get;set;} 
  3.  
  4.     public JsonStringsss(JSONParser parser) {
  5.         while (parser.nextToken() != JSONToken.END_OBJECT) {
  6.             if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
  7.                 String text = parser.getText();
  8.                 if (parser.nextToken() != JSONToken.VALUE_NULL) {
  9.                     if (text == 'type') {
  10.                         type_Z = parser.getText();
  11.                     } else if (text == 'auth-cookies') {
  12.                         authcookies = new List<String>();
  13.                         while (parser.nextToken() != JSONToken.END_ARRAY) {
  14.                             authcookies.add(new String(parser));
  15.                         }
  16.                     } else {
  17.                         System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
  18.                         consumeObject(parser);
  19.                     }
  20.                 }
  21.             }
  22.         }
  23.     }