+ Start a Discussion
SolidLucasSolidLucas 

Trigger help before insert

Hello,well i've created a trigger that updates a campaign member status to answered,but i need to improve my code,cause actually i've hardcoded the Id of the campaign that i wish to update the member status,what i want to know is there any way to set the campaign without setting the Id hardcoded,cause this will impact in the future. thanks!
this is my code!
trigger bi_WebToCaseLead on Case (before insert) {

List<CampaignMember> listCm = [SELECT Id,Lead.Email,LeadId,CampaignId FROM CampaignMember WHERE CampaignId = '701190000001F5l'];
Map<String, CampaignMember> mapCm = new Map<String, CampaignMember>();

    for(CampaignMember cm : listCm){
        mapCm.put(cm.Lead.Email, cm);
    }
    for(Case caso : Trigger.new){
        Case tempCase = caso;
        CampaignMember tempCampaign = mapCm.get(caso.SuppliedEmail);
        if(tempCampaign != null && caso.ChaveCampanha__c == '701190000001F5l'){
          tempCampaign.Status = 'Respondido';
          caso.RelacionamentoLead__c = tempCampaign.LeadId;
          update tempCampaign;        
        }
    }
}

 
William TranWilliam Tran
Sure,

Since the trigger is on the case, how about creating a variable on the case storing the campaign.  
That way the SOQL just need to reference the campaign of the case.

As a common practice, if your question is answered, please choose 1 best answer. 
But you can give every answer a thumb up if that answer is helpful to you. 

Thanks
JeffreyStevensJeffreyStevens
A couple of things:
So - it looks like you're doing this only for a specific campaign.  I'm thinging you should add a flag to the campaign object for - "Update member status ...".  Then in your trigger - you can get all (probably just this one) campaign to get the ID.

Also - you'll have an issue doing the DML update in a loop with your existing code. 
SolidLucasSolidLucas
I see,but the update happens when the user fill the web to case form. Actually i'm checking the campaign Id and the SupliedEmail of the user.
Abhishek BansalAbhishek Bansal
Hi,

As per your requirement i have modified your code.
Please change your trigger code with below code :
 
trigger bi_WebToCaseLead on Case (after insert) {
	Set<String> caseEmails = new Set<String>();
	
	for(Case caso : trigger.new){
		caseEmails.add(caso.SuppliedEmail);
	}
	
	Map<String, CampaignMember> mapCm = new Map<String, CampaignMember>();
	for(CampaignMember cm : [SELECT Id,Lead.Email,LeadId,CampaignId FROM CampaignMember WHERE Lead.Email IN :caseEmails]){
		mapCm.put(cm.Lead.Email, cm);
	}
	List<CampaignMember> campaignToUpdateList = new List<CampaignMember>();
	List<Case> caseListToUpdate = new List<Case>();
	for(Case caso : Trigger.new){
        Case tempCase = caso;
        CampaignMember tempCampaign = mapCm.get(caso.SuppliedEmail);
        if(tempCampaign != null && caso.ChaveCampanha__c == '701190000001F5l'){
          tempCampaign.Status = 'Respondido';
          caso.RelacionamentoLead__c = tempCampaign.LeadId;
          update tempCampaign;        
        }
        
        if(mapCm.containsKey(caso.SuppliedEmail) && caso.ChaveCampanha__c == '701190000001F5l'){
        	caso.RelacionamentoLead__c = mapCm.get(caso.SuppliedEmail).LeadId;
        	caseListToUpdate.add(caso);
        	mapCm.get(caso.SuppliedEmail).Status = 'Respondido';
        	campaignToUpdateList.add(mapCm.get(caso.SuppliedEmail));
        }
    }
	if(trigger.isInsert && caseListToUpdate.size() > 0){
		update caseListToUpdate;
	}
	if(campaignToUpdateList.size() > 0){
		update campaignToUpdateList;
	}
}

Let me know if you need more help on this or if you have any issue in this.

Thanks,
Abhishek Bansal
SolidLucasSolidLucas

Hey,Abhishek! First,thanks for your help, i tried to use your code but it didn't work,the update happens after the user fill the web to case form,the test i was doing is to pass the web to case url with the campaign Id,but it didn't update the case,so i  created the before trigger to check the values before update the status.

here is my web to case:
 
<form id="Formulario" action="https://cs24.salesforce.com/servlet/servlet.WebToCase?encoding=UTF-8" method="POST">

    <link rel="stylesheet" type="text/css" href="w2c.css">
    <script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

  <!-- JavaScript que insere valor no campo escondido -->
    <script type='text/javascript'>
    	function abc(){
    		var Id = gup("Id",window.location.href);
    		document.getElementById("00N19000000WNoN").value = Id;
    		alert("Agradecemos o seu interesse!");
    	}
    	function gup(name,email, url ) {
    	  if (!url) url = location.href
    		  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    		  var regexS = "[\\?&]"+name+"=([^&#]*)";
    		  var regex = new RegExp( regexS );
    		  var results = regex.exec( url );
    		  return results == null ? null : results[1];
    		}
    </script>

    <input type=hidden name="orgid" value="00D19000000DMeE">
  

  
       
        <p>
          <label class="field-label">Nome*:</label><input  id="name" class="campo" maxlength="80" name="name" size="30" type="text" placeholder="Informe seu nome" required />
        </p>

        <p>
          <label  class="field-label"  for="email">Email*:</label><input  id="email" class="campo" maxlength="80" name="email" size="30" type="text" placeholder="Informe seu email" required/>
        </p>  
        <p>
          <label class="field-label" for="phone">Telefone*:</label><input  id="phone" class="campo" maxlength="40" name="phone" size="30" type="text" placeholder="Informe o telefone" required/>
        </p>

        <p>
          <label class="field-label" for="subject">Assunto*:</label><input  id="subject" class="campo" maxlength="80" name="subject" size="30" type="text" placeholder="Informe o assunto" required />
        </p>

        <p>
          <label class="field-label" for="company">Empresa*:</label><input  id="company" class="campo" maxlength="80" name="company" size="30" type="text" placeholder="Informe o nome da Empresa"required/>
        </p>

        <p>
          <label class="field-label" for="description">Descrição*:</label><textarea name="description" class="fieldarea" rows="4" cols="31"></textarea>
        </p>
      
    	<!-- Chave Campanha -->
      	<input  id="00N19000000WNoN" maxlength="15" name="00N19000000WNoN" size="30" type="hidden" /><br>

      <!-- Botão enviar -->
    	<div style="padding-left:100px;">
    		<input class="submit" onclick="abc()" type="submit" name="submit">
    	</div>
    </form>
  </div>
</div>