• Shyam Bhundia
  • SMARTIE
  • 574 Points
  • Member since 2014
  • Developer @ FCA


  • Chatter
    Feed
  • 18
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 135
    Replies
Dear all,

I have made 2 triggers to create an event when a condition is true and another one to send the link by mail when the event is created.
Now I need help to build a test class for these triggers because test coverage is 0%

Here are my triggers :

trigger TriggerEventForCustomerToContact on Amcor_Surveys__c (After insert)
{
     set<id> setamcorIds= new set<id>();
For (Amcor_Surveys__c ams : trigger.new)
{
  If(ams.Q6_NeedAmcorToContactYou__c == 'Yes')
  {
     setamcorIds.add(ams.Id);
  }
}

list<Amcor_Surveys__c> listSelectedAmcor= [select Account_ID__r.OwnerId,Contact_ID__c
                                            from  Amcor_Surveys__c
              where id in :setamcorIds];
System.debug('Creating event record');

list<Event> listEventToCreate= new list<Event> ();
for(Amcor_Surveys__c ams :listSelectedAmcor)
{
  //create an event record
  Event ev = new Event();
  Ev.Business_group__c ='Amcor Flexibles Europe & Americas';
  Ev.Whatid = ams.id;
  ev.RecordTypeId='012g00000004ajF';//'Visit Report VOC';
  ev.Type ='Customer Satisfaction Survey';
  ev.DurationInMinutes = 720;
  ev.Ownerid = ams.Account_ID__r.OwnerId;
  ev.whoId =ams.Contact_ID__c;
  ev.Subject ='Customer Satisfaction Survey - Customer contact' ;
  ev.objective__c = 'Improve Relationship';
  //System.debug('************ ' + system.today());
  Date startDate = system.today();
  ev.ActivityDate = startDate;
  ev.StartDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 9);
   ev.ActivityDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 09);
  Date EndDate = startdate +5;
  System.debug('Attempting to insert...');
  
  listEventToCreate.add(ev);
    }
try{
insert listEventToCreate;
}
catch(Exception e)
{
  System.debug(e.getMessage());
  }
}





trigger Trigger_Event_Send_Email on Event (After insert) 
{ 
         for(Event evt: Trigger.New)
 if(evt.type == 'Customer Satisfaction Survey'){
 
    Set<Id> ownerIds = new Set<Id>();
    Set<Id> initiatorIds = new Set<Id>();
    Set<Id> amsIds = New Set<Id>();
    Set<Id> AccIds = New Set<Id>();
   
//Value in AssignedTO
        ownerIds.add(evt.OwnerId);
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);
  
//Value in CreatedBy
        initiatorIds.add(evt.CreatedById);
    Map<Id, User> userMap2 = new Map<Id,User>([select Name, Email from User where Id in :initiatorIds]);  

//Related To WhatId = Opportunity
        amsIds.add(evt.WhatId);
    Map<id, Amcor_Surveys__c > amsMap = new Map<Id,Amcor_Surveys__c>([select Name from Amcor_Surveys__c where Id in :amsIds]);
    
//Related To WhatId = Account
        AccIds.add(evt.WhatId);
    Map<id, Account> AccMap = new Map<Id,Account>([select Name from Account where Id in :AccIds]);   

// parameters

        String Whatid ;
        User User = userMap2.get(evt.CreatedById);
        User Assignee = userMap.get(evt.ownerId); 
        if(amsMap.containsKey(evt.whatid)){
            Whatid = amsMap.get(evt.WhatId).Name;
        }
        if(AccMap.containsKey(evt.whatid)){
            Whatid = AccMap.get(evt.WhatId).Name;
        }  
        
// email config           
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {Assignee.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('VOC Survey : A new event is added in your Calendar');    // Set the subject

       String template = 'Hello {0}, \nThe following Visit Report has been created for you :\n';
        
        String duedate = '';       
        template+= '\n';
        template+= 'Due Date - {1}\n';
        template+= 'Type - {2}\n';     
        template+= 'Subject - {3}\n';
        template+= 'Assign To - {4}\n';
        template+= 'Related To - {5}\n';   
        template+= '\n';
        template+='Click on the following link to access the Visit Report:\n';
        template+= '{6}\n';
        
// Check field Send Email Alert
//   If(System.now() == evt.Send_Email_Alert__c )   
//        evt.SendEmailAlert__c = True;
         
// calculate end date of event
        if (evt.EndDateTime ==null)
            duedate = '';
        Else
           duedate = evt.EndDateTime.format();
                  
        List<String> args = new List<String>();

        args.add(Assignee.Name);
        args.add(duedate);
        args.add(evt.type);
        args.add(evt.subject);
        args.add(Assignee.Name);
        args.add(whatid);
        args.add('https://'+System.URL.getSalesforceBaseURL().getHost()+'/'+evt.Id);
        
// Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
     
            
           // }
    }
    }


And I have modified an existing test class on triggers but code coverage is not changing on my trigger :(
From : // Test Triggers TriggerEventForCustomerToContact to 
//
// This class contains unit tests for validating all Triggers 
//
@isTest
private class TriggerTests {

    private static testMethod void triggersTestAccountUpdate(){
        Profile p = [select id from profile where name='Standard User'];
        User u = new User(alias = 'standt', email='standarduser4@testorg.com',emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id, timezonesidkey='America/Los_Angeles', username='TESTUSER1234@testorg.com');
        System.runAs(u) {   
        
        // account update
        Account A = new Account();
        A.Name = 'Test A';
        try{
            insert A;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        Account A1 = ([Select Id from Account where Name='Test A' limit 1]);
        //A1.Last_Object_Updated_Delta__c = 5;
        update A1;
        
        List <Account> acclist = ([Select Id from Account where Name='Test A']);
        String createdbyId = UserInfo.getName();
        String UserProfileId = UserInfo.getProfileId();
        for (Account acc:acclist) {
        
        double Delta = 100;

        // if the Last_Modified_Date_Time__c hasn't been modified for the last second then it is an account update
        if (Delta >1){
            if (UserProfileId != '00e20000000ju28AAA'){
                    String ModifiedDateTime = '';
                    Datetime cDT = System.now();
                    ModifiedDateTime = cDT.format('d/MM/yyyy hh:mm a');
                    // Compose the Modified_By with user name and update date/time 
                    acc.Last_Modified_By__c = createdbyId +', '+ ModifiedDateTime;
                    acc.Last_Object_Modified__c='Account';
                    // This last one re-introduced by Carl V on 24th, to address navigation request.
                    acc.Last_Updated_Date_Time__c = cDT;
            }
        }   
        }
        
        // Opportunity update
        Opportunity Op = new Opportunity();
        Op.Name = 'Op test';
        Op.Type = 'Volume Change';
        Op.accountId = A.id;
        Op.Unadj_Expected_Annual_Impact__c = 101.01;
        Op.Expected_PM_of_New_Volume__c = 12;
        Op.Expected_Units_Annually__c = 5;
        Op.Actual_Units_Annually__c = 12;
        Op.StageName = 'Idea Action';
        Op.CloseDate = system.today();
        
        try{
            insert Op;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // AC update
        
        Amcor_Contract__c AC = new Amcor_Contract__c();
        AC.Name = 'AC test';
        AC.Account__c = A.id;
        try{
            insert AC;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // ACP update
        Amcor_Contract_Portfolio__c ACP = new Amcor_Contract_Portfolio__c();
        ACP.CurrencyIsoCode = 'AUD';
        ACP.Account__c = A.id;
        try{
            insert ACP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // ACT update
        Amcor_Contract_Term__c ACT = new Amcor_Contract_Term__c();
        ACT.CurrencyIsoCode = 'AUD';
        ACT.Account__c = A.id;
        try{
            insert ACT;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // AE update
        Account_Economics__c AE = new Account_Economics__c();
        AE.CurrencyIsoCode = 'AUD';
        AE.Account__c = A.id;
        try{
            insert AE;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // attachement
        Attachment At = new Attachment();
        At.ParentId = A.id;
        At.Name = 'test At';
        At.Body = Blob.valueOf( 'this is an attachment test' );
        insert At;
        
        // BAI update
        Basic_Account_Intelligence__c BAI = new Basic_Account_Intelligence__c();
        BAI.CurrencyIsoCode = 'AUD';
        BAI.Account__c = A.id;
        try{
            insert BAI;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // BAI update
        Bottom_Performing_Amcor_Product__c BPAP = new Bottom_Performing_Amcor_Product__c();
        BPAP.Name = 'Test BPAP';
        BPAP.Account__c = A.id;
        try{
            insert BPAP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // CNA update
        Customer_Needs_Assessment__c CNA = new Customer_Needs_Assessment__c();
        CNA.CurrencyIsoCode = 'AUD';
        CNA.Account__c = A.id;
        try{
            insert CNA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // CRA update
        Competitive_Risk_Assessment__c CRA = new Competitive_Risk_Assessment__c();
        CRA.Name = 'Test CRA';
        CRA.Account__c = A.id;
        try{
            insert CRA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // KF Insert
        Key_Financials__c KF = new Key_Financials__c();
        KF.CurrencyIsoCode = 'AUD';
        KF.Account__c = A.id;
        try{
            insert KF;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // KPI Insert
        Key_Performance_Indicator__c KPI = new Key_Performance_Indicator__c();
        KPI.CurrencyIsoCode = 'AUD';
        KPI.Account__c = A.id;
        try{
            insert KPI;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // KTM Insert
        Account_Team_Member__c KTM = new Account_Team_Member__c();
        KTM.CurrencyIsoCode = 'AUD';
        KTM.Account__c = A.id;
        try{
            insert KTM;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // LL Insert
        Largest_Leakage__c LL = new Largest_Leakage__c();
        LL.Name = 'Test LL';
        LL.Account__c = A.id;
        try{
            insert LL;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // NA Insert
        Note NA = new Note();
        NA.Title = 'Test Note';
        NA.ParentId = A.id;
        try{
            insert NA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // OB Insert
        Business_with_other_BGs_BUs__c OB = new Business_with_other_BGs_BUs__c();
        OB.CurrencyIsoCode = 'AUD';
        OB.Account__c = A.id;
        try{
            insert OB;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // RSA Insert
        Risk_of_Substitution_Assessment__c RSA = new Risk_of_Substitution_Assessment__c();
        RSA.Name = 'Test RSA';
        RSA.Account__c = A.id;
        try{
            insert RSA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // SMRA Insert
        Self_Manufacturing_Risk_Assessment__c SMRA = new Self_Manufacturing_Risk_Assessment__c();
        SMRA.Name = 'Test SMRA';
        SMRA.Account__c = A.id;
        try{
            insert SMRA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // STL Insert
        Ship_to_Location__c STL = new Ship_to_Location__c();
        STL.Name = 'Test STL';
        STL.Account__c = A.id;
        try{
            insert STL;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // Task Insert
        Task Ta = new Task();
        Ta.Type = 'Test Ta';
        Ta.WhatId = A.id;
        try{
            insert Ta;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // TCP Insert
        Top_Customer_Product__c TCP = new Top_Customer_Product__c();
        TCP.Name = 'Test TCP';
        TCP.Account__c = A.id;
        try{
            insert TCP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // TPAP Insert
        Top_Performing_Amcor_Product__c TPAP = new Top_Performing_Amcor_Product__c();
        TPAP.Name = 'Test TPAP';
        TPAP.Account__c = A.id;
        try{
            insert TPAP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // VPD Insert
        Value_Proposition__c VPD = new Value_Proposition__c();
        VPD.CurrencyIsoCode = 'AUD';
        VPD.Account__c = A.id;
        try{
            insert VPD;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // Contact Insert
        Contact Co = new Contact();
        Co.Email = 'testcontact@test.com';
        Co.AccountId = A.id;
        try{
            insert Co;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        

 // Test Triggers TriggerEventForCustomerToContact
 
        Amcor_Surveys__c amsv = new Amcor_Surveys__c();
        amsv.Account_ID__c = a.id ;//'TEST COMPANY';
        amsv.Contact_ID__c = co.id ;//'Ludivine Jobit'
        amsv.Q6_NeedAmcorToContactYou__c ='Yes';
        try{
            insert amsv;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }

     set<id> setamcorIds= new set<id>();
 
   If(amsv.Q6_NeedAmcorToContactYou__c == 'Yes')
  {
     setamcorIds.add(amsv.Id);
  }


list<Amcor_Surveys__c> listSelectedAmcor= [select Account_ID__r.OwnerId,Contact_ID__c
                                            from  Amcor_Surveys__c
                                              where id in :setamcorIds];
                                              System.debug('Creating event record');

list<Event> listEventToCreate= new list<Event> ();
for(Amcor_Surveys__c ams :listSelectedAmcor)
{
      
        // Event Insert
        Event Ev = new Event();
  Ev.Business_group__c ='Amcor Flexibles Europe & Americas';
  Ev.Whatid = ams.id;
  ev.RecordTypeId='012g00000004ajF';//'Visit Report VOC';
  ev.Type ='Customer Satisfaction Survey';
  ev.DurationInMinutes = 720;
  ev.Ownerid =p.id ;
  ev.whoId =co.id;
  ev.Subject ='Customer Satisfaction Survey - Customer contact' ;
  ev.objective__c = 'Improve Relationship';
  //System.debug('************ ' + system.today());
  Date startDate = system.today();
  ev.ActivityDate = startDate;
  ev.StartDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 9);
   ev.ActivityDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 09);
  Date EndDate = startdate +5;
  
 listEventToCreate.add(ev);
 }
        try{
            insert listEventToCreate;
                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
   //Fire Email for Event Customer Satisfaction Survey
        //tbd 
        
  // end tests 
    }
}








I am using the below code

trigger AddToPG on Contact (after insert, after update) {
    List<GroupMember> GMlist = new List<GroupMember>();
    for(Contact U : Trigger.New) {
        if(U.Add_to_Group__c == TRUE) {
            GroupMember GM = new GroupMember();
            GM.GroupId = '00Gg0000000afKH';
            GM.UserOrGroupId = U.Id;
            GMList.add(GM);        
        }
    }

        insert GMList;
    }

However, this is giving the below error

Error:Apex trigger AddToPG caused an unexpected exception, contact your administrator: AddToPG: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, User/Group ID: id value of incorrect type: 003g000000HfUsiAAF: [UserOrGroupId]: Trigger.AddToPG: line 12, column 1

I think this is because I am trying the set the contact ID where I should be using the User or Group ID. The contacts will be Partner users so they will have a user record. Are there any changes I can make to my trigger which will allow me to do this?
Hey everyone, Im fairly  new to APEX and need some guidance through this simple error. The error i receive is the Method void DeleteContact() is referenced by VisualForce page(cls) in salesforce.com. Remove the usage and try again.
This is pointing to the void DeleteInventory in the controller, so I am not sure what this error is exactly pointing.

cls page
<apex:page controller="clsController" sidebar="true" showheader="false" showChat="true" >

<html>
  <head>
    <title></title>
        <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet" 

media="screen"/>    

   <style>
      body {
        padding-top: 60px;
         }
     
    </style>
  </head>
  <body>
       <script src="http://code.jquery.com/jquery-latest.js"></script>
       <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js"></script>
    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="#">Computer Inventory</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="#else">Contact</a></li>
            </ul>
          </div>        
          </div>
      </div>
    </div>

    <div class="container">



 <apex:form id="form">
<apex:image value="{!$Resource.LogoAbel}" width="30%" />
  <apex:pageBlock title="Computer Inventory">
  <apex:pageMessages >
</apex:pageMessages>
  <apex:pageBlockButtons >
          <apex:commandButton action="{!save}" value="Save"/>
  </apex:pageBlockButtons>
 <apex:pageBlock >
     <apex:panelgrid columns="2">
     <apex:selectList value="{!selectedField }" size="1">
     <apex:selectOption itemValue="Employee_Name__c" itemLabel="EmployeeName"/>
     <apex:selectOption itemValue="ASI_Solutions_Inventory_Number__c" itemLabel="ASI Solutions Inventory Number"/>
     <apex:selectOption itemValue="Location__c" itemLabel="Location"/>
     <apex:selectOption itemValue="Make__c" itemLabel="Make"/>
     <apex:selectOption itemValue="Model__c" itemLabel="Model"/>
     <apex:selectOption itemValue="Purchase_Date__c" itemLabel="Purchase Date"/>
     <apex:selectOption itemValue="Serial_Number__c" itemLabel="Serial Number"/>
     <apex:selectOption itemValue="Warranty__c" itemLabel="Warranty"/>
     <apex:selectOption itemValue="Vendor__c" itemLabel="Vendor"/>    
     </apex:selectList>
    <apex:commandButton value="Click Here to Sort" action="{!sortMethod}" reRender="pgblcktbl"/>
   </apex:panelgrid>
  </apex:pageBlock>
  <apex:pageBlock >
  
   <apex:pageblocktable value="{!inventories}" var="rec" id="pgblcktbl" >
  
   <apex:column >       
<apex:outputLink title="" value="/{!rec.id}/e?retURL=/apex/{!$CurrentPage.Name}" style="font-weight:bold">Edit</apex:outputLink>&nbsp;|&nbsp;       
<a href="javascript:if (window.confirm('Are you sure?')) DeleteInventory('{!rec.Id}');" style="font-weight:bold">Del</a>     
</apex:column> 
   
     <apex:column value="{!rec.Employee_Name__c}"/>
     <apex:column value="{!rec.ASI_Solutions_Inventory_Number__c}"/>
      <apex:column value="{!rec.Location__c}"/>
       <apex:column value="{!rec.Make__c}"/>
       <apex:column value="{!rec.Model__c}"/>
        <apex:column value="{!rec.Purchase_Date__c}"/>
        <apex:column value="{!rec.Serial_Number__c}"/>
        <apex:column value="{!rec.Warranty__c}"/>
        <apex:column headerValue="Vendor">
          <apex:inputField value="{!rec.Vendor__c}"/>
        </apex:column>   
  </apex:pageblocktable>
   
  
  </apex:pageBlock>
    
  </apex:pageBlock>
     <apex:actionFunction action="{!DeleteInventory}" name="DeleteInventory" reRender="form" >   
<apex:param name="inventoriesid" value="" assignTo="{!selectedField}"/>
</apex:actionFunction>
 
 </apex:form>
     </div> 
      </body>
</html>
</apex:page>



here is the controller
public with sharing class clsController 
{

    public List<Inventory__c> inventories {get;set;}
    public List<Inventory__c> con {get; set;}
    public string selectedField {get;set;}
    public clsController()
    {
    LoadData();
    }
       
    public void LoadData()
    { 
    
         inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c Limit 10];
     } 
    
   public void DeleteInventory()   {      
    
    if (SelectedField == null) 
    {      
    return;     
     }        
 Inventory__c tobeDeleted = null;     
  for(Inventory__c a: inventories)        
         if (a.Id == SelectedField) 
         {          
         tobeDeleted = a;  break;       
         }         
         
if (tobeDeleted != null) {      
 Delete tobeDeleted;      }          
         
         LoadData();   }       
          
            
  public void sortMethod()
  {
  if (selectedField =='Employee_Name__c')
  inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Employee_Name__c Limit 10];
        
  else if(selectedField == 'ASI_Solutions_Inventory_Number__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by ASI_Solutions_Inventory_Number__c Limit 10];
        
 else if(selectedField ==  'Make__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by  Make__c Limit 10];
        
else if(selectedField == 'Model__c')
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Model__c Limit 10];
        
else if(selectedField == 'Purchase_Date__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Purchase_Date__c Limit 10];
        
else if(selectedField == 'Serial_Number__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Serial_Number__c Limit 10];
       
else if(selectedField == 'Vendor__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by  Vendor__c Limit 10];
        
else if(selectedField == 'Warranty__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Warranty__c Limit 10];
        
else if(selectedField ==  'Location__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Location__c Limit 10];
  
  }
   
  public void save()
    {
    update inventories;
    }
    

}
thank you for any help

Hi folks,
           Can anyone tell me how to display the list of id values???
My apex class is:
public class ListIdValues{
    public static List<Id> IdValues(){
        list<Id> a=new list<Id>();
        a.add('00E90000000eytMEH1');
        a.add('00E90000000eytMEH1');
        a.add('00E90000000eytMEH1');
        a.add('00E90000000eytMEH1');
        a.add('00E90000000eytMEH1');
        return a;
    }
}
I tried like
List<id> lis=ListIdValues.IdValues();
for(Integer j=0;j<lis.size();j++)
    System.debug('list values='+ lis[j]);

how to display all the values in anonymous window??


Hi, 
I'm tring to write a text file with this information:
Quote1
QuoteLineItem1
QuoteLineItem2
QuoteLineItem3 ....

Quote2
QuoteLineItem1
QuoteLineItem2
QuoteLineItem3 .... etc

I'm able to write all the info for Quote1 and Quote2 etc, but I'm not able to write the details info for each Quote after each Quote record.

I have a button calling a VF page calling a controller 
Here is my Class 
public class IDR
{

    public Media__c media {get;set;}
    public List <Quote> LstQuotes { get; set; }
    public List <QuoteLineItem> LstQuotelineitem { get; set; }
  
    public void fetch()
    {
     String theId =  Apexpages.currentpage().getparameters().get('City');
     String strMediaID =  Apexpages.currentpage().getparameters().get('MediaId');       
               
     media = [SELECT m.City_Code__c, m.Name, m.Current_Issue_Date__c FROM Media__c m WHERE City_Code__c =
     :theId];
 
   LstQuotes = [SELECT q.id,q.QuoteNumber, q.Ad_Name__c,q.Type__c, q.Size__c,  q.Version__c, q.Bleed_Code__c,
   (Select QuoteLineItem.Id, QuoteLineItem.QuoteId From QuoteLineItems)
   From Quote q
   where City_Code__c = :theId and q.Media_Name__c =: strMediaID];


       
  for(Quote q:LstQuotes )
   {
       for (QuoteLineItem qli : q.QuoteLineItems)
       {
           // I can see my subquery info here. Now how can I send it back to my VF page?
            system.debug('Quote Line Items Records ' + qli.id );
         
       }
   }
     
  }   

}
/*********/
Here is my VF page

<apex:page Controller="IDR" sidebar="false" action="{!fetch}" contentType="text/plain/#emp.txt" cache="false">

{"mediaCode":"{!media.City_Code__c}","mediaName":"{!media.Name}","issueDate":"
<apex:outputText value="{0,date,yyyyMMdd}">
<apex:param value="{!media.Current_Issue_Date__c}" />
</apex:outputText>","secondWrap":false,"ads":[

<apex:repeat value="{!LstQuotes}" var="Listrec">
{"adId":"<apex:outputText value="{!Listrec.QuoteNumber}" />
","filename"<apex:outputText value="{!Listrec.Ad_Name__c}" />
,"type"<apex:outputText value="{!Listrec.Type__c}" />
,"size"<apex:outputText value="{!Listrec.Size__c}" />
,"version"<apex:outputText value="{!Listrec.Version__c}" />
,"section"<apex:outputText value="{!Listrec.Ad_Name__c}" />
,"bleedCode"<apex:outputText value="{!Listrec.Bleed_Code__c}" />
,"properties":["propertyid":

<apex:repeat value="{!LstQuotelineitem}" var="Listrec2">
// I think my details records have to be here.
</apex:repeat>

</apex:repeat>


</apex:page>

Thanks...

When i click on save button through this below url:

https://ap1.salesforce.com/001/e?retURL=%2F001%2Fo

In trigger i am trying to get the full url including query parameters, even though it has retURL as query parameter i am getting null when i use URL.getCurrentRequestUrl().getQuery().

On click of save button i standard page, I want to get the query string in trigger please reply if any one know how to get it.

Thank you.......
populate list of all address_for_contac__c field on contac to Final_address_of_contacts__c on account field
suppose (addres fields)
contact 1 : a
contact 2 :c
so in account
Final address of contacts :a ,c

in this trigger its coming
Final address of contacts : http://,a


trigger listOfContactsOnAccount on contact (after insert , after update)

{ set<id> con = new set<id>();
 
           if( trigger.isInsert|| trigger.isUpdate)
           for(contact c : trigger.new)
            {
            con.add(c.AccountId);
            }
  
            if(trigger.isDelete)
            for(contact c: trigger.old)
            {
             con.add(c.AccountId);
            }
          
    //2.create map
  
    List<contact> cont = [ Select AccountId , Address_for_contact__c from contact where AccountId IN : con ]; 
    Map<id,contact> maps = new map<id,contact>();
  
  
            for(contact c :cont)
            {
          
            maps.put(c.accountId,c);
          
            }
  
    //3 create trigger.new to match each recore
      list<account> acConAddress = new list<account>();
      String l  = '';
  

  
     list<Account>  ac = [select id, Final_Address_of_Contacts__c from account where Id IN :con];
     
  
           for(account act : ac)
         
             {    contact co = maps.get(act.Id);
                  string local= co.Address_for_Contact__c;
                  l=l+','+local;        
                  act.Final_address_of_contacts__c = l;
                  acConAddress.add(act);
             }
         update acConAddress;
}
public void deleteAttachment(){
        Attachment attc = [SELECT Id, Name from Attachment WHERE Id = :attachId];
        delete(attc);
    }
How would I write test coverage for this function?
Hi,

I'm trying to send an email scheduling by a date field in my task:
global class Email_agendado_Impressao implements Schedulable {

    global void execute(SchedulableContext sc) {
    
        for (Task t: [select Id, E_mail__c, Data_do_pedido__c from Task where subject = 'Fotos faltantes - Envio de Backup']){

        if (t.Data_do_pedido__c == system.today()){

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
          String[] toAddresses = new String[]{};   
            toAddresses.add(t.e_mail__c);
          mail.setToAddresses(toAddresses);
            
            mail.setSenderDisplayName('Test email');

          mail.setSubject('Test Schedule');
          mail.setPlainTextBody('Test email');
        }
        }
    }
}

I had scheduled, but I didn't receive the email.

Probably my code is wrong, it is my first time scheduling.

What should I do?

Thanks !
Hello- I'm new to visualforce and this is my first project.  Through the online guides and examples I have been able to accomplish almost everything.  I'm trying to increase my code coverage.  It is currently at 66%.

This is my controller:
public with sharing class CommentsController {

	private final Case cas;
		   
    //
    public String MasterRecordId        {get; set;}
    public List<Case_Comments__c> ChildRecords  {get; set;}
    public Case MasterRecord                 {get; set;}

    //SET UP PAGE
    public CommentsController(ApexPages.StandardController stdController) {
    		this.cas = (Case)stdController.getRecord();
		MasterRecordId = ApexPages.currentPage().getParameters().get('id');

		 //CHECK FOR ID
        if(!String.isBlank(MasterRecordId)){

            //GET PARENT
            MasterRecord =
                [
                    SELECT 
                        Id,
                        CaseNumber
                    FROM
                        Case
                    WHERE
                        Id = :MasterRecordId
                ];

            //GET CHILD RECORDS
            ChildRecords =
                [
                    SELECT 
                        Name,
						Id,
                        CreatedDate,
                        CreatedBy.Id,
                        CreatedBy.Name,
                        Time_Spent__c,
                        Comment__c,
                        ParentId__c
                    FROM
                        Case_Comments__c
                    WHERE 
                        ParentId__c = :MasterRecordId order by CreatedDate desc
                ];
        }
    }

}

This is my test class:

@isTest
	public class testCommentsController {
    	static testMethod void testFirstTest() {

        // CREATE ACCOUNT
		Account newAccount = new Account(Name = 'Test Account', Phone='817-999-9999');
		insert newAccount;
      
        // CREATE CONTACT
		Contact newContact = new Contact(LastName = 'Test Contact', AccountId = newAccount.Id);
		insert newContact;  
		       		        
        // CREATE CASE
        Case newCase = new Case(Subject = 'Case Subject', Description = 'Case Description', ContactId = newContact.Id, AccountId = newAccount.Id);
        insert newCase;  
        
        // CREATE CASE COMMENT
        Case_Comments__c newComment = new Case_Comments__c(ParentId__c = newCase.Id, Comment__c = 'Test Comment Body', Time_Spent__c = .5);
        insert newComment;

        ApexPages.StandardController sc = new ApexPages.StandardController(newCase);
        CommentsController cc = new CommentsController (sc);

        PageReference pageRef = Page.Comments;
        pageRef.getParameters().put('id', String.valueOf(newCase.Id));
        Test.setCurrentPage(pageRef);
			
        }
}

I can tell from the test coverage highlights that the case "MasterRecord" and the list "ChildRecords" from the controller are not covered.  I assume that I would need to assert that MasterRecord = the case, and that ChildRecords ParentId__c = MasterRecord Id.  I do not know how to do that.  I do not know how to reference them in my test class or if that is right.  Any help would be appreciated.

  • August 14, 2014
  • Like
  • 0
I have a JavaScript button that merely copies and pastes field values from one record type to another. My problem is that anytime I have a text box with a carraige return (user has hit the Return key), I get an "unterminated string constant" error. How do I remove these characters so that my button will work? I've used differet variations of the following syntax: 
URL = URL.replace(/\r?\n|\r/g, “ “);
<apex:page standardController="account" recordSetVar="items">
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!items}" var="vartodisplay">
<apex:column value="{!vartodisplay.name}"/>
<apex:column value="{!vartodisplay.industry}"/>
<apex:column value="{!vartodisplay.rating}"/>
<apex:column value="{!vartodisplay.website}"/>
<apex:column value="{!vartodisplay.phone}"/>
<apex:column value="{!vartodisplay.parentid}"/>

</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
I am trying to figure out how to take a variable that is declared and set within a method in a controller and use it in a VF page.  Here is what I have code-wise to explain what I am wanting to do.  First the main controller:

public class VfSearchController_Adam { 

	public VfSearchController_Adam(){

		Boolean bpUser;

		GetUserType gut = new GetUserType();

		bpUser = gut.isBPUser();
	}
}

It is making a call to the following class:

public class GetUserType { 
    
    public GetUserType () {}
            
    User u = [SELECT AccountId,UserType,Name FROM User WHERE  Id =: Userinfo.getUserId()];
            
    public Boolean isBPUser(){
    
        List<Account> acct = [SELECT Best_Practice_Buyer__c FROM Account WHERE  Id =:u.AccountId];
    
        return acct[0].Best_Practice_Buyer__c;
    }    
}

Now, everything is working perfectly here.  The value of "bpUser" is being set as desired.  However, I have the following VF Component as well:

<apex:component controller="VfSearchController_Adam">

	<apex:variable var="foo" value="bar" rendered="{!bpUser}">
	
		<li class="itemMenu"><a href="{!$Site.CurrentSiteUrl}">BP Center</a></li>
		
	</apex:variable>  

</apex:component>


How do I make the "bpUser" variable, which is declared and populated in a method within the VFSearchController_Adam class, available in my VF page?

I have a feeling that it just won't work the way it is in the VF component right now.  I have seen variables set at the very beginning of the main class such as:

public Boolean bpUser {get;set;}
but declaring the variable like that in the main class, not within the method, prevents the variable from being populated at all.

Suggestions?
if  i save a new account , then cloned account shud also b created.
this trigger is showing no error bt , when i save the new acount only that accnt issaved nt the clone account of it .


trigger partneracClone on account (after update) {

// accounts ids to query
Account[] accToClone = new Account[]{};
Account [] accToSave = new Account[]{};

Set<Id> AccountIds = new Set<Id>();
For(account acc : trigger.new)
{
     AccountIds.add(acc.id);
accToClone.add(acc);
}

// query accounts and store by there name to lookup it up quickly
    Map<Id,Account> accountMap = new Map<Id,Account>([
        select  Id  , Name,Description,Phone,Fax  from Account where Id IN: AccountIds]);

    // clone
    for (Account acc :accToClone)
    {   Account theClone = new Account();


       
        theClone.Name =  accountMap.get(acc.id).Name;
        theClone.Type =  accountMap.get(acc.id).Type;
        theClone.Phone =  accountMap.get(acc.id).Phone;

        theClone.Fax =  accountMap.get(acc.id).Fax;
        theClone.Description =  accountMap.get(acc.id).Description;

        accToSave.add(theClone);
    }

    insert accToSave;

  

}
Hi, 

  I created a css file inside folder name cssexample 

style.css file name
================
h1
{
  text-align:center;
  color:green;
}


made 
cssexample.zip and uploaded in static resources


I am calling in visual force page it is not referencing Please suggest me what is the issue

<apex:page standardstylesheets="false" showheader="false">

<apex:stylesheet value="{!URLFOR($Resource.cssex, 'style.css')}" />

<h1> This text is displayed using CSS </h1>
</apex:page>
Hi All,

I am trying to work out a way to populate a customer lead field by cross reference with a customer object, i will be doing this in APEX code as i believe its not possible as a workflow. 

Situation

We are using apex classes to create lead records using information sent into salesforce from a webserver.

SO, the apex code populates the below custom field
lead.abicode__c = 1234567


We then want lead.abigroup to update. As there is a large number of abicodes we have created a custom object ( abigroups16062014) and this contains around 30000 records showing two bits of information:

EG:
abigroups16062014.code = 1234567
abigroups16062014.group = 27

What i want to happen is when the lead is created, i would like a piece of code that will allow lead.abigroup__c to be populated with the corresponding group number from the custom object. 

so

find abigroup16062014.code where .code = l.abicode__c
then
l.abigroup__c = abigroup16062014.group

Does this make sense?


trigger realtime2 on Contact (before insert)
  {

     map<id,string> map1=new map<id,string>();
     list<contact> conlist=new list<contact>();
      list<contact> conlist1=new list<contact>();
if(trigger.isbefore)
    {
    for (Contact con:trigger.new)
     {
       map1.put(con.id,con.phone);
       conlist.add(con);
     }
      for(contact con:conlist)
      {        
       con.mobilephone=map1.get(con.id);
       conlist1.add(con);
     }
    
  update conlist1;
   }
  }
Hi All,

   I have question - 
  I created one object 'sampleObject' with one field 'Name' in it and visualforce page and controller code as follows

Visualforce page code :

   <apex:page controller="SampleClass">
    <apex:form id="RID">
        <apex:pageBlock title="Sample Edit" mode="edit">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>           
            </apex:pageBlockButtons>
            <apex:pageBlockSection title="Basic Information" columns="1">
                <apex:inputText label="Name" value="{!sampleObj.Name__c}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Code : 

public class SampleClass {

    public sampleObject__c sampleObj { get; set; }

    public PageReference save() {     
        System.Debug(sampleObj.Name__c);
        return null;
    }
}


Now whenever I click on save button it gives me error - 

System.NullPointerException: Attempt to de-reference a null object
Error is in expression '{!save}' in component <apex:commandButton> in page samplepage: Class.SampleClass.save: line 6, column 1

Can anyone tell me where am I going wrong ?

Thanks,
Abhishek
Dear all,

I have made 2 triggers to create an event when a condition is true and another one to send the link by mail when the event is created.
Now I need help to build a test class for these triggers because test coverage is 0%

Here are my triggers :

trigger TriggerEventForCustomerToContact on Amcor_Surveys__c (After insert)
{
     set<id> setamcorIds= new set<id>();
For (Amcor_Surveys__c ams : trigger.new)
{
  If(ams.Q6_NeedAmcorToContactYou__c == 'Yes')
  {
     setamcorIds.add(ams.Id);
  }
}

list<Amcor_Surveys__c> listSelectedAmcor= [select Account_ID__r.OwnerId,Contact_ID__c
                                            from  Amcor_Surveys__c
              where id in :setamcorIds];
System.debug('Creating event record');

list<Event> listEventToCreate= new list<Event> ();
for(Amcor_Surveys__c ams :listSelectedAmcor)
{
  //create an event record
  Event ev = new Event();
  Ev.Business_group__c ='Amcor Flexibles Europe & Americas';
  Ev.Whatid = ams.id;
  ev.RecordTypeId='012g00000004ajF';//'Visit Report VOC';
  ev.Type ='Customer Satisfaction Survey';
  ev.DurationInMinutes = 720;
  ev.Ownerid = ams.Account_ID__r.OwnerId;
  ev.whoId =ams.Contact_ID__c;
  ev.Subject ='Customer Satisfaction Survey - Customer contact' ;
  ev.objective__c = 'Improve Relationship';
  //System.debug('************ ' + system.today());
  Date startDate = system.today();
  ev.ActivityDate = startDate;
  ev.StartDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 9);
   ev.ActivityDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 09);
  Date EndDate = startdate +5;
  System.debug('Attempting to insert...');
  
  listEventToCreate.add(ev);
    }
try{
insert listEventToCreate;
}
catch(Exception e)
{
  System.debug(e.getMessage());
  }
}





trigger Trigger_Event_Send_Email on Event (After insert) 
{ 
         for(Event evt: Trigger.New)
 if(evt.type == 'Customer Satisfaction Survey'){
 
    Set<Id> ownerIds = new Set<Id>();
    Set<Id> initiatorIds = new Set<Id>();
    Set<Id> amsIds = New Set<Id>();
    Set<Id> AccIds = New Set<Id>();
   
//Value in AssignedTO
        ownerIds.add(evt.OwnerId);
    Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);
  
//Value in CreatedBy
        initiatorIds.add(evt.CreatedById);
    Map<Id, User> userMap2 = new Map<Id,User>([select Name, Email from User where Id in :initiatorIds]);  

//Related To WhatId = Opportunity
        amsIds.add(evt.WhatId);
    Map<id, Amcor_Surveys__c > amsMap = new Map<Id,Amcor_Surveys__c>([select Name from Amcor_Surveys__c where Id in :amsIds]);
    
//Related To WhatId = Account
        AccIds.add(evt.WhatId);
    Map<id, Account> AccMap = new Map<Id,Account>([select Name from Account where Id in :AccIds]);   

// parameters

        String Whatid ;
        User User = userMap2.get(evt.CreatedById);
        User Assignee = userMap.get(evt.ownerId); 
        if(amsMap.containsKey(evt.whatid)){
            Whatid = amsMap.get(evt.WhatId).Name;
        }
        if(AccMap.containsKey(evt.whatid)){
            Whatid = AccMap.get(evt.WhatId).Name;
        }  
        
// email config           
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {Assignee.Email};
        mail.setToAddresses(toAddresses);    // Set the TO addresses
        mail.setSubject('VOC Survey : A new event is added in your Calendar');    // Set the subject

       String template = 'Hello {0}, \nThe following Visit Report has been created for you :\n';
        
        String duedate = '';       
        template+= '\n';
        template+= 'Due Date - {1}\n';
        template+= 'Type - {2}\n';     
        template+= 'Subject - {3}\n';
        template+= 'Assign To - {4}\n';
        template+= 'Related To - {5}\n';   
        template+= '\n';
        template+='Click on the following link to access the Visit Report:\n';
        template+= '{6}\n';
        
// Check field Send Email Alert
//   If(System.now() == evt.Send_Email_Alert__c )   
//        evt.SendEmailAlert__c = True;
         
// calculate end date of event
        if (evt.EndDateTime ==null)
            duedate = '';
        Else
           duedate = evt.EndDateTime.format();
                  
        List<String> args = new List<String>();

        args.add(Assignee.Name);
        args.add(duedate);
        args.add(evt.type);
        args.add(evt.subject);
        args.add(Assignee.Name);
        args.add(whatid);
        args.add('https://'+System.URL.getSalesforceBaseURL().getHost()+'/'+evt.Id);
        
// Here's the String.format() call.
        String formattedHtml = String.format(template, args);
       
        mail.setPlainTextBody(formattedHtml);
        Messaging.SendEmail(new Messaging.SingleEmailMessage[] {mail});
     
            
           // }
    }
    }


And I have modified an existing test class on triggers but code coverage is not changing on my trigger :(
From : // Test Triggers TriggerEventForCustomerToContact to 
//
// This class contains unit tests for validating all Triggers 
//
@isTest
private class TriggerTests {

    private static testMethod void triggersTestAccountUpdate(){
        Profile p = [select id from profile where name='Standard User'];
        User u = new User(alias = 'standt', email='standarduser4@testorg.com',emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id, timezonesidkey='America/Los_Angeles', username='TESTUSER1234@testorg.com');
        System.runAs(u) {   
        
        // account update
        Account A = new Account();
        A.Name = 'Test A';
        try{
            insert A;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        Account A1 = ([Select Id from Account where Name='Test A' limit 1]);
        //A1.Last_Object_Updated_Delta__c = 5;
        update A1;
        
        List <Account> acclist = ([Select Id from Account where Name='Test A']);
        String createdbyId = UserInfo.getName();
        String UserProfileId = UserInfo.getProfileId();
        for (Account acc:acclist) {
        
        double Delta = 100;

        // if the Last_Modified_Date_Time__c hasn't been modified for the last second then it is an account update
        if (Delta >1){
            if (UserProfileId != '00e20000000ju28AAA'){
                    String ModifiedDateTime = '';
                    Datetime cDT = System.now();
                    ModifiedDateTime = cDT.format('d/MM/yyyy hh:mm a');
                    // Compose the Modified_By with user name and update date/time 
                    acc.Last_Modified_By__c = createdbyId +', '+ ModifiedDateTime;
                    acc.Last_Object_Modified__c='Account';
                    // This last one re-introduced by Carl V on 24th, to address navigation request.
                    acc.Last_Updated_Date_Time__c = cDT;
            }
        }   
        }
        
        // Opportunity update
        Opportunity Op = new Opportunity();
        Op.Name = 'Op test';
        Op.Type = 'Volume Change';
        Op.accountId = A.id;
        Op.Unadj_Expected_Annual_Impact__c = 101.01;
        Op.Expected_PM_of_New_Volume__c = 12;
        Op.Expected_Units_Annually__c = 5;
        Op.Actual_Units_Annually__c = 12;
        Op.StageName = 'Idea Action';
        Op.CloseDate = system.today();
        
        try{
            insert Op;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // AC update
        
        Amcor_Contract__c AC = new Amcor_Contract__c();
        AC.Name = 'AC test';
        AC.Account__c = A.id;
        try{
            insert AC;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // ACP update
        Amcor_Contract_Portfolio__c ACP = new Amcor_Contract_Portfolio__c();
        ACP.CurrencyIsoCode = 'AUD';
        ACP.Account__c = A.id;
        try{
            insert ACP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // ACT update
        Amcor_Contract_Term__c ACT = new Amcor_Contract_Term__c();
        ACT.CurrencyIsoCode = 'AUD';
        ACT.Account__c = A.id;
        try{
            insert ACT;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // AE update
        Account_Economics__c AE = new Account_Economics__c();
        AE.CurrencyIsoCode = 'AUD';
        AE.Account__c = A.id;
        try{
            insert AE;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // attachement
        Attachment At = new Attachment();
        At.ParentId = A.id;
        At.Name = 'test At';
        At.Body = Blob.valueOf( 'this is an attachment test' );
        insert At;
        
        // BAI update
        Basic_Account_Intelligence__c BAI = new Basic_Account_Intelligence__c();
        BAI.CurrencyIsoCode = 'AUD';
        BAI.Account__c = A.id;
        try{
            insert BAI;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // BAI update
        Bottom_Performing_Amcor_Product__c BPAP = new Bottom_Performing_Amcor_Product__c();
        BPAP.Name = 'Test BPAP';
        BPAP.Account__c = A.id;
        try{
            insert BPAP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // CNA update
        Customer_Needs_Assessment__c CNA = new Customer_Needs_Assessment__c();
        CNA.CurrencyIsoCode = 'AUD';
        CNA.Account__c = A.id;
        try{
            insert CNA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // CRA update
        Competitive_Risk_Assessment__c CRA = new Competitive_Risk_Assessment__c();
        CRA.Name = 'Test CRA';
        CRA.Account__c = A.id;
        try{
            insert CRA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // KF Insert
        Key_Financials__c KF = new Key_Financials__c();
        KF.CurrencyIsoCode = 'AUD';
        KF.Account__c = A.id;
        try{
            insert KF;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // KPI Insert
        Key_Performance_Indicator__c KPI = new Key_Performance_Indicator__c();
        KPI.CurrencyIsoCode = 'AUD';
        KPI.Account__c = A.id;
        try{
            insert KPI;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // KTM Insert
        Account_Team_Member__c KTM = new Account_Team_Member__c();
        KTM.CurrencyIsoCode = 'AUD';
        KTM.Account__c = A.id;
        try{
            insert KTM;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // LL Insert
        Largest_Leakage__c LL = new Largest_Leakage__c();
        LL.Name = 'Test LL';
        LL.Account__c = A.id;
        try{
            insert LL;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // NA Insert
        Note NA = new Note();
        NA.Title = 'Test Note';
        NA.ParentId = A.id;
        try{
            insert NA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // OB Insert
        Business_with_other_BGs_BUs__c OB = new Business_with_other_BGs_BUs__c();
        OB.CurrencyIsoCode = 'AUD';
        OB.Account__c = A.id;
        try{
            insert OB;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // RSA Insert
        Risk_of_Substitution_Assessment__c RSA = new Risk_of_Substitution_Assessment__c();
        RSA.Name = 'Test RSA';
        RSA.Account__c = A.id;
        try{
            insert RSA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // SMRA Insert
        Self_Manufacturing_Risk_Assessment__c SMRA = new Self_Manufacturing_Risk_Assessment__c();
        SMRA.Name = 'Test SMRA';
        SMRA.Account__c = A.id;
        try{
            insert SMRA;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // STL Insert
        Ship_to_Location__c STL = new Ship_to_Location__c();
        STL.Name = 'Test STL';
        STL.Account__c = A.id;
        try{
            insert STL;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // Task Insert
        Task Ta = new Task();
        Ta.Type = 'Test Ta';
        Ta.WhatId = A.id;
        try{
            insert Ta;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // TCP Insert
        Top_Customer_Product__c TCP = new Top_Customer_Product__c();
        TCP.Name = 'Test TCP';
        TCP.Account__c = A.id;
        try{
            insert TCP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // TPAP Insert
        Top_Performing_Amcor_Product__c TPAP = new Top_Performing_Amcor_Product__c();
        TPAP.Name = 'Test TPAP';
        TPAP.Account__c = A.id;
        try{
            insert TPAP;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // VPD Insert
        Value_Proposition__c VPD = new Value_Proposition__c();
        VPD.CurrencyIsoCode = 'AUD';
        VPD.Account__c = A.id;
        try{
            insert VPD;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
        // Contact Insert
        Contact Co = new Contact();
        Co.Email = 'testcontact@test.com';
        Co.AccountId = A.id;
        try{
            insert Co;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        

 // Test Triggers TriggerEventForCustomerToContact
 
        Amcor_Surveys__c amsv = new Amcor_Surveys__c();
        amsv.Account_ID__c = a.id ;//'TEST COMPANY';
        amsv.Contact_ID__c = co.id ;//'Ludivine Jobit'
        amsv.Q6_NeedAmcorToContactYou__c ='Yes';
        try{
            insert amsv;                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }

     set<id> setamcorIds= new set<id>();
 
   If(amsv.Q6_NeedAmcorToContactYou__c == 'Yes')
  {
     setamcorIds.add(amsv.Id);
  }


list<Amcor_Surveys__c> listSelectedAmcor= [select Account_ID__r.OwnerId,Contact_ID__c
                                            from  Amcor_Surveys__c
                                              where id in :setamcorIds];
                                              System.debug('Creating event record');

list<Event> listEventToCreate= new list<Event> ();
for(Amcor_Surveys__c ams :listSelectedAmcor)
{
      
        // Event Insert
        Event Ev = new Event();
  Ev.Business_group__c ='Amcor Flexibles Europe & Americas';
  Ev.Whatid = ams.id;
  ev.RecordTypeId='012g00000004ajF';//'Visit Report VOC';
  ev.Type ='Customer Satisfaction Survey';
  ev.DurationInMinutes = 720;
  ev.Ownerid =p.id ;
  ev.whoId =co.id;
  ev.Subject ='Customer Satisfaction Survey - Customer contact' ;
  ev.objective__c = 'Improve Relationship';
  //System.debug('************ ' + system.today());
  Date startDate = system.today();
  ev.ActivityDate = startDate;
  ev.StartDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 9);
   ev.ActivityDateTime = Datetime.newInstanceGmt(startDate.year(), startDate.month(), startDate.day(), 0, 0, 09);
  Date EndDate = startdate +5;
  
 listEventToCreate.add(ev);
 }
        try{
            insert listEventToCreate;
                          
        } catch (System.DmlException e){
            System.debug('we caught a dml exception: ' + e.getDmlMessage(0));    
        }
        
   //Fire Email for Event Customer Satisfaction Survey
        //tbd 
        
  // end tests 
    }
}








Hi All,
           I have a List button that shown for all profiles view, I need to resitrict the button to show only for Technician Profile, How can set the accessablity to that button? like field level security. 
I am using the below code

trigger AddToPG on Contact (after insert, after update) {
    List<GroupMember> GMlist = new List<GroupMember>();
    for(Contact U : Trigger.New) {
        if(U.Add_to_Group__c == TRUE) {
            GroupMember GM = new GroupMember();
            GM.GroupId = '00Gg0000000afKH';
            GM.UserOrGroupId = U.Id;
            GMList.add(GM);        
        }
    }

        insert GMList;
    }

However, this is giving the below error

Error:Apex trigger AddToPG caused an unexpected exception, contact your administrator: AddToPG: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, User/Group ID: id value of incorrect type: 003g000000HfUsiAAF: [UserOrGroupId]: Trigger.AddToPG: line 12, column 1

I think this is because I am trying the set the contact ID where I should be using the User or Group ID. The contacts will be Partner users so they will have a user record. Are there any changes I can make to my trigger which will allow me to do this?
Hi all,

I have a field in detail page which is text field 
and i want to write a  formule field so tht i have to change the text which is in tht text field to number as the return type in formule field is number


can any one please help out from this with syntax of changing the text value to number
Hi, 

I am trying to creat Master-Deatail Realtionship between the Account and the Order Object.
But when i clicked New Filed in ORDER object, there is no Master-detail Relationship DataType Option :(

Why ? it is not showing ?

Hi,

My requirement is if i select any picklist value in custome field it has to popup related value on another customer field.

Let me explaine in detail, i have two fields like medical procedure(picklist) and price field.  If i select any picklist value in medical procedure it has to be popup price field with related value.

Please SHARE, Does anyone has some sample code or can point me in the right direction?
Many thanks!!!
  • August 29, 2014
  • Like
  • 0
Hi,

My requirement is if i select any picklist value in custome field it has to popup related value on another customer field.

Let me explaine in detail, i have two fields like medical procedure(picklist) and price field.  If i select any picklist value in medical procedure it has to be popup price field with related value.

Please share, Does anyone has some sample code or can point me in the right direction?
Many thanks!!!
  • August 29, 2014
  • Like
  • 0
How can show an error message if a field in a tab is null near a button in the same tab on click it.othervice load a new url in a new window?
  • August 29, 2014
  • Like
  • 0
Hey everyone, Im fairly  new to APEX and need some guidance through this simple error. The error i receive is the Method void DeleteContact() is referenced by VisualForce page(cls) in salesforce.com. Remove the usage and try again.
This is pointing to the void DeleteInventory in the controller, so I am not sure what this error is exactly pointing.

cls page
<apex:page controller="clsController" sidebar="true" showheader="false" showChat="true" >

<html>
  <head>
    <title></title>
        <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet" 

media="screen"/>    

   <style>
      body {
        padding-top: 60px;
         }
     
    </style>
  </head>
  <body>
       <script src="http://code.jquery.com/jquery-latest.js"></script>
       <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/js/bootstrap.min.js"></script>
    <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </a>
          <a class="brand" href="#">Computer Inventory</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li class="active"><a href="#">Home</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="#else">Contact</a></li>
            </ul>
          </div>        
          </div>
      </div>
    </div>

    <div class="container">



 <apex:form id="form">
<apex:image value="{!$Resource.LogoAbel}" width="30%" />
  <apex:pageBlock title="Computer Inventory">
  <apex:pageMessages >
</apex:pageMessages>
  <apex:pageBlockButtons >
          <apex:commandButton action="{!save}" value="Save"/>
  </apex:pageBlockButtons>
 <apex:pageBlock >
     <apex:panelgrid columns="2">
     <apex:selectList value="{!selectedField }" size="1">
     <apex:selectOption itemValue="Employee_Name__c" itemLabel="EmployeeName"/>
     <apex:selectOption itemValue="ASI_Solutions_Inventory_Number__c" itemLabel="ASI Solutions Inventory Number"/>
     <apex:selectOption itemValue="Location__c" itemLabel="Location"/>
     <apex:selectOption itemValue="Make__c" itemLabel="Make"/>
     <apex:selectOption itemValue="Model__c" itemLabel="Model"/>
     <apex:selectOption itemValue="Purchase_Date__c" itemLabel="Purchase Date"/>
     <apex:selectOption itemValue="Serial_Number__c" itemLabel="Serial Number"/>
     <apex:selectOption itemValue="Warranty__c" itemLabel="Warranty"/>
     <apex:selectOption itemValue="Vendor__c" itemLabel="Vendor"/>    
     </apex:selectList>
    <apex:commandButton value="Click Here to Sort" action="{!sortMethod}" reRender="pgblcktbl"/>
   </apex:panelgrid>
  </apex:pageBlock>
  <apex:pageBlock >
  
   <apex:pageblocktable value="{!inventories}" var="rec" id="pgblcktbl" >
  
   <apex:column >       
<apex:outputLink title="" value="/{!rec.id}/e?retURL=/apex/{!$CurrentPage.Name}" style="font-weight:bold">Edit</apex:outputLink>&nbsp;|&nbsp;       
<a href="javascript:if (window.confirm('Are you sure?')) DeleteInventory('{!rec.Id}');" style="font-weight:bold">Del</a>     
</apex:column> 
   
     <apex:column value="{!rec.Employee_Name__c}"/>
     <apex:column value="{!rec.ASI_Solutions_Inventory_Number__c}"/>
      <apex:column value="{!rec.Location__c}"/>
       <apex:column value="{!rec.Make__c}"/>
       <apex:column value="{!rec.Model__c}"/>
        <apex:column value="{!rec.Purchase_Date__c}"/>
        <apex:column value="{!rec.Serial_Number__c}"/>
        <apex:column value="{!rec.Warranty__c}"/>
        <apex:column headerValue="Vendor">
          <apex:inputField value="{!rec.Vendor__c}"/>
        </apex:column>   
  </apex:pageblocktable>
   
  
  </apex:pageBlock>
    
  </apex:pageBlock>
     <apex:actionFunction action="{!DeleteInventory}" name="DeleteInventory" reRender="form" >   
<apex:param name="inventoriesid" value="" assignTo="{!selectedField}"/>
</apex:actionFunction>
 
 </apex:form>
     </div> 
      </body>
</html>
</apex:page>



here is the controller
public with sharing class clsController 
{

    public List<Inventory__c> inventories {get;set;}
    public List<Inventory__c> con {get; set;}
    public string selectedField {get;set;}
    public clsController()
    {
    LoadData();
    }
       
    public void LoadData()
    { 
    
         inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c Limit 10];
     } 
    
   public void DeleteInventory()   {      
    
    if (SelectedField == null) 
    {      
    return;     
     }        
 Inventory__c tobeDeleted = null;     
  for(Inventory__c a: inventories)        
         if (a.Id == SelectedField) 
         {          
         tobeDeleted = a;  break;       
         }         
         
if (tobeDeleted != null) {      
 Delete tobeDeleted;      }          
         
         LoadData();   }       
          
            
  public void sortMethod()
  {
  if (selectedField =='Employee_Name__c')
  inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Employee_Name__c Limit 10];
        
  else if(selectedField == 'ASI_Solutions_Inventory_Number__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by ASI_Solutions_Inventory_Number__c Limit 10];
        
 else if(selectedField ==  'Make__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by  Make__c Limit 10];
        
else if(selectedField == 'Model__c')
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Model__c Limit 10];
        
else if(selectedField == 'Purchase_Date__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Purchase_Date__c Limit 10];
        
else if(selectedField == 'Serial_Number__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Serial_Number__c Limit 10];
       
else if(selectedField == 'Vendor__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by  Vendor__c Limit 10];
        
else if(selectedField == 'Warranty__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Warranty__c Limit 10];
        
else if(selectedField ==  'Location__c') 
     inventories = [select Employee_Name__c, ASI_Solutions_Inventory_Number__c, Make__c, Model__c, Purchase_Date__c, Serial_Number__c,
        Vendor__c, Warranty__c, Location__c from inventory__c where id IN:inventories order by Location__c Limit 10];
  
  }
   
  public void save()
    {
    update inventories;
    }
    

}
thank you for any help

Hello, 
I am participating in development of project, where we must use database of my homecountry Addresses. This database can be downloaded as xml. My problem is that there are 4 files. Two small (less than 1 mb), one which is 30 mb and one 70 mb. There are also some relations between those files, like: region name is mapped to some number in file A , and in file B we only have Region code. I am wondering how to input this database into salesforce, so that later whole database can be used. So far i came with such idea:
-write Java program to process all files and split them into smaller files (for example containing only information about one region, in my caountry there is 16 of them)
-upload them as documents/static resources
-write apex class to parse theese xml files and save records as, some custom object address
Problem with such approach would be that i would have to provide custom application, and it should be easy to use, so that employees coudl update salesforce database. And this database is updated daily,  i assume that they would like to update it once a week.
Have anyone faced such problem?
trigger realtime2 on Contact (before insert)
  {

     map<id,string> map1=new map<id,string>();
     list<contact> conlist=new list<contact>();
      list<contact> conlist1=new list<contact>();
if(trigger.isbefore)
    {
    for (Contact con:trigger.new)
     {
       map1.put(con.id,con.phone);
       conlist.add(con);
     }
      for(contact con:conlist)
      {        
       con.mobilephone=map1.get(con.id);
       conlist1.add(con);
     }
    
  update conlist1;
   }
  }
Hi,

I'm writing a delete trigger and that is bulkify too. I'm not getting the way to prevent valid data of being delete. like for example if I have 10 record to delete and 2 of them are valid or supposed not to be deleted by anyone. so my use case is those 2 recoreds should will not be deleted . and rest all (8) can be deleted easily.

so if anyone knows about it then please let me know. thanks in advance.