• KevSnell
  • NEWBIE
  • 5 Points
  • Member since 2011

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 64
    Replies

Hi All.

 

I'm hoping someone can help with this simple fix.

 

I have the following code below that looks at a lead field called custom field hubspot_campaign_c (this has a campaign ID in) and if it is not null it adds the lead to the specific campaign listed in hubspot_campaign_c.

 

trigger LeadToCampaign on Lead (after update, after insert) {
 
for (Lead l: trigger.new) {

if (l.HubSpot_Campaign__c != null ) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; //You will have to know the ID or query for it or something
                cm.Status = 'Responded'; //Or whatever default status you want on the member
                
            insert cm;

}
}
}

 

This works perfectly fine but it generates an error if the lead record is updated because the lead will already exist in the campaign.

 

So what I need help on is to add a line which queries the campaignmembers and checks to see if the lead already exists for the campaignID listed in the custom field hubspot_campaign_c.

 

So what I was trying to do was create a list of campaign members where the leadID matches in the campaign member list but this is where I got stuck.  This will generate a list of campaigns the lead is in and I then need to filter it by campaignid = hubspot_campaign_c and then if campaignmember list is null add the campaign member.  

 

trigger LeadToCampaign on Lead (after update, after insert) {

List<Id> leads=new List<Id>();

for (Lead l: trigger.new) {

List<CampaignMember> cms=[Select LeadID, CampaignID FROM CampaignMember WHERE LeadID IN: leads];
        
if (l.HubSpot_Campaign__c != null) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; //You will have to know the ID or query for it or something
                cm.Status = 'Responded'; //Or whatever default status you want on the member
                
            insert cm;

}
}
}

 

Any help would be much appreciated.


Kev

Hi all,

 

I have a problem with the below trigger and need some help.

 

This is what the trigger shoud do:

 

  1. If Campaign.IsActive = True then change CampaignMember.Campaign_Acitve__c = True
  2. If Campaign.IsActive = False and the CampaignMember.Campaign_Acitve__c = New then change CampaignMember.Campaign_Acitve__c = FalseUpdate
  3. If Campaign.IsActive = False and current CampaignMember.Campaign_Acitve__c != New then change CampaignMember.Campaign_Acitve__c = False

However I can't get 2 & 3 to work, here's my code:

 

trigger trgr_Campaign_ActiveCampaign_au  on Campaign (after update) {

    CampaignMember[] CampaignMembersRelatedToCampaignBatch = [ select CampaignID, Campaign_Active__c from CampaignMember where CampaignId in :Trigger.new ];

    for(CampaignMember currentCampaignMember : CampaignMembersRelatedToCampaignBatch ) {
        Campaign CampaignMemberParentCampaign = Trigger.newMap.get( currentCampaignMember.CampaignID ); 
        
        if(CampaignMemberParentCampaign.IsActive == True) {
            currentCampaignMember.Campaign_Active__c = 'True';
        }

        if(CampaignMemberParentCampaign.IsActive == False && currentCampaignMember.Campaign_Active__c == 'New') {
            currentCampaignMember.Campaign_Active__c = 'FalseUpdate';
        }
        
        if(CampaignMemberParentCampaign.IsActive == False && currentCampaignMember.Campaign_Active__c != 'New') {
            currentCampaignMember.Campaign_Active__c = 'False';
        } 
        
    }
      
    update CampaignMembersRelatedToCampaignBatch;

}

 

Any help would really be appreciated.

Thanks

Kev 

 

 

Hey All,


Not sure what is going on here especially as it's a simple trigger.

 

As you can see the trigger flags an error if anyone other than a Systems Administrator tries to delete a Completed Task.

 

trigger trgr_Task_PreventDelete_bd on Task (Before delete) {

    for (Integer i = 0; i < Trigger.Old.size(); i++) {
        if (Trigger.Old[i].Status == 'Complete' && UserInfo.getProfileId() != '00eE0000000XjEM') {
               // Cannot delete this task
               Trigger.Old[i].addError('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator.');
        }
    }
}

 

So my logic was create a lead and task and then try to delete while running as a user other than a system admin but it doesn't work.

 

@isTest
private class test_trgr_PreventTaskDelete{
    public static testMethod void testDeleteFail()
    {
        User rep = [Select Profileid from User where Name = 'Test Chair' limit 1];
        System.runAs(rep)
        {
        System.debug('VistageDebug: entering TriggerTests_Campaign_ActiveCampaign_Before_Delete');
        
        Lead l2 = new Lead(OwnerID = '005E0000000YhNn',Status = 'New',Company = 'Test',LastName = 'Test',LeadSource = 'Advertising',Industry = 'Fitness');
        Insert l2;

    //Setup t2 and relate to L2
        Task t2 = new Task(OwnerID = '005E0000000YhNn',Subject = 'test',Type = 'Cold Call',Status = 'Not Started',Priority = 'Normal',WhoId = l2.id);
        insert t2;
    
    //Update t2
        Task updateMe = [SELECT Id FROM Task WHERE Id = :t2.Id];
        updateMe.Status = 'Completed';
        update updateMe;
        
        Task TaskDelete = [SELECT Id FROM Task WHERE Id = :t2.Id];
           try
               {
                delete TaskDelete;
                  // should throw an exception - the following assertion will cause an error if the code carries on
                  System.assert(false);
               }
               catch (DMLException e)
               {
               // expected - could assert the message here
               }
           }
        }
}

 

Any help would be highly appreciated as one moment I think I'm starting to understand things and then the next moment I hit another road block.

 

Thanks

Kevin 

Hi, 

 

I have an issue with the below code I'm developing.  It seems I get the error "System.FinalException: Record is read-only"

 

Looking at the debug code it is caused by line 18 - if( CampaignMemberParentCampaign.IsActive = True) 

 

Can anyone help as I haven't come across this before.

Thanks

Kev 

 

 

trigger CampaignMemberStatus on Campaign (after update) {
    for( Campaign currentNewCampaign : Trigger.new ) 
    {
      Campaign correspondingOldCampaign = Trigger.oldMap.get( currentNewCampaign.Id );
      
      //if( currentNewCampaign.Physical_Street__c != correspondingOldCampaign.Physical_Street__c) 
      //{
      //  currentNewCampaign.Physical_Street_prior__c = correspondingOldCampaign.Physical_Street__c;
      //}
    }

      CampaignMember[] CampaignMembersRelatedToCampaignBatch = [ select CampaignID, Campaign_Active_V2__c from CampaignMember
      where CampaignId in :Trigger.new ];

      for( CampaignMember currentCampaignMember : CampaignMembersRelatedToCampaignBatch ) 
      {
        Campaign CampaignMemberParentCampaign = Trigger.newMap.get( currentCampaignMember.CampaignID );
        if( CampaignMemberParentCampaign.IsActive = True) 
        {
        currentCampaignMember.Campaign_Active_V2__c = 'true';
        }
      }

    update CampaignMembersRelatedToCampaignBatch;
}

 

 

Hi All,


I'm trying to find a solution for the following:

 

When the Campaign is set to Active it updates a custom field (CampaignField__c) in all Campaign Members for that Campaign.

 

I can't seem to find any examples when it comes to triggers with Campaigns.

 

I think the logic is:

  1. After Update
  2. Query CampaignMembers
  3. If Campaign ISActive = True
  4. Then CampaignField__c on CampaignMembers = True

Thanks

Kev 

Hi all,

 

I have created Campaign Member number field (Campaign_Active__c) which is either 1(active) or -1(inactive) depending on whether the campaign is active.  This updates when the Campaign is changed from active to inactive.

I now need to create a trigger which adds or subtracts a score from the lead scoring field (Campaign_Score__c) depending on the Campaign_Active__c.

 

I did a search and found some code and tried modifying it but currently am not being very succesfully so an help would be appreciated.  

 

trigger CampaignMemberAfter on CampaignMember(after insert, after update, after delete)
{
    Map<Id,CampaignMember> campaignLeads = new Map<Id,CampaignMember>{};
    List<CampaignMember> camMembers = trigger.IsInsert || trigger.IsUpdate ? trigger.new : trigger.old;
    
    for(CampaignMember cm : camMembers)
        campaignLeads.put(cm.LeadId, cm);
 
    List<Lead> consToUpdate = new List<Lead>{};
 
    for(Lead con : [Select Id, Campaign_Score__c from Lead where Id in :campaignLeads.keySet()])
    {
        if(trigger.isInsert || trigger.isUpdate) 
        con.Campaign_Score__c += campaignLeads.get(con.Id).Campaign_Active__c;
 
        else if (trigger.isDelete)
        con.Campaign_Score__c += campaignLeads.get(con.Id).Campaign_Active__c;
 
        consToUpdate.add(con);
    }
}

 

 

 

Hey all,


Is it possible to create a field in the Lead fields that shows whether a lead is in any active campaigns or not?

 

For example: It doesn't matter if they are in one active campaign or three active campaigns it would shows as true and if no campaign it would be false.

 

Thanks

Kev 

Hi all,

 

I'm sure this is possible but I currently can't find the answer so looking for some help or direction.

 

I want to create a drop down in a VF page that is a list of active users with their associated ID so when a user is selected from the dropdown the ID is added to the below query replacing the userinfo.getuserid.  

 

Public static  integer getWeb_Corporate()
    {
    integer Web_Corporate = [SELECT count() FROM Lead where OwnerId =:UserInfo.getUserId() AND LeadSource='Web-Corporate' AND IsConverted = False AND List_Assignment__c != 'Corporate'  LIMIT 1000];
    return Web_Corporate ;
    }    

 


Any help would be appreciated.

Kev 


 

Hi All,


I have the following query which I have tested and works in SoqlXplorer.

 

SELECT Member__c, (SELECT Joined_Date__c,Joined__c FROM Opportunities__r WHERE Joined_Date__c = LAST_N_DAYS:365) FROM Contact WHERE Member__c = TRUE LIMIT 1000

 

However, my issue is I want to count the results ie like the below but this query results in MALFORMED_QUERY: Grouped query cannot use child relationships in the SELECT list

 

SELECT Count(ID), (SELECT Joined_Date__c,Joined__c FROM Opportunities__r WHERE Joined_Date__c = LAST_N_DAYS:365) FROM Contact WHERE Member__c = TRUE LIMIT 1000

 

Can anyone help.


Thanks


Kev

 

Hi All,

 

One thing I have yet to find the answer to is how do you test exceptions.  For example I have two exceptions one in a Class and the other in a Trigger, yet I can't seem to find the answer on how to test these.

 

If anyone can help here are the two different exceptions:

 

Apex Class:

catch(Exception ex)
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,ex.getMessage()));
}

 

Apex Trigger:

catch (DmlException de)
{
for ( integer i = 0; i < de.getNumDml(); i++ )
{
System.debug('Lead_Referral Error Inserting Lead Referral Objects: ' + de.getDmlMessage(i));
} 

 

Any help or guidance would really be appreciated.


Thanks

Kev 

 

Hi All,

 

I have created a Task Controller and Visualforce Page so a User can click a button on a custom object and it will create a prepopulated Task.  Meaning the User then just needs to click "Create Task".  This all works fine, however, still being an amature I can't get the TestMethod to work. 

 

If anyone could point me in the right direction I would really appreciate it.

 

public class Custom_Referral_Task_Controller { 
 
    Id idReferralClass = null;
    public Referral__c ReferralCurrent {get;set;}
    public Task tskNew {get;set;}

    public void createTaskRecord() {

        tskNew = new Task();
   
        tskNew.OwnerId = '005E0000000YhNn';
        tskNew.WhoId = '003M0000008jjA5';
        tskNew.WhatId = 'a06M0000002pW2o';
        tskNew.Subject = 'Referral Validation';
        tskNew.ActivityDate = date.today() + 7;
        tskNew.ReminderDateTime = datetime.now() + 7;
        tskNew.Description = 'Test Task'; // Pull concatenated text see above
    }

    public PageReference saveAndProceed() {

       
        //Insert Task
        try {
            insert tskNew;

        } 
        catch(DMLException e) {
            tskNew.addError(e.getMessage());
            return null;
        }

        // Return URL to Referral Object
        PageReference pf = new PageReference('/' + ReferralCurrent.Id);
        pf.setRedirect(true);
        return pf;
    }

}

 

So I tried creating the below TestMethod, however, I get 0% coverage.  I think my issue is I'm not actual testing the controller but I'm not sure where I am going wrong.

 

static testmethod void testCustomReferralTaskController() {

	try
	{
	
    Test.startTest();
    	//Create Referrer
    	VistageTestData data = new VistageTestData();
    	Account[] testAccounts = data.gimmeAccounts(2);
    	Contact testContact = data.gimmeContacts(testAccounts)[0];
    	Contact testContactDetails = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
    	testContactDetails.Staff__c = true;
    	update testContactDetails;
    
	//Create Referral
	VistageTestData data2 = new VistageTestData();
	Account[] testAccounts2 = data2.gimmeAccounts(2);
	Contact testContact2 = data2.gimmeContacts(testAccounts)[0];
	Contact testContactDetails2 = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
	testContactDetails2.Member__c = true;
	update testContactDetails2;    
    
	Referral__c Referral = new Referral__c(
        Referrer__c = testContactDetails.Id,
        Contact_Referral_Name__c = testContactDetails2.Id
		);
        insert Referral;
            
	Task testTask = new Task (
		WhoId = testContactDetails2.Id,
		WhatId = Referral.Id,
		Subject = 'Referral Validation',
		ActivityDate = date.today() + 7,
		ReminderDateTime = datetime.now() + 7,
		Description = 'Please Validate the Referral');
	insert testTask; 
    
   	Task t = [Select Id, whoid from Task where WhatId = :Referral.Id Limit 1];
   	system.assertEquals(t.whoid,testContactDetails2.Id);
   	Test.stopTest();
	
	}
	catch(exception e)
	{
		system.assertequals(e,null);
	}

} 

 

Many thanks in advance for any help or guidance.


Kev

 

Hi All,

 

I'm slowly understanding the apex code but the testmethods are still outwitting me.

 

I created the below custom controller which loads a custom New Task Page prepopulated from a Custom Object so the User can submit the task without having to fill in the details.

 

This works great, however, I can't figure out the testmethod.  As far as I understand I need to create the data, create the task and confirm the task was created.

 

So as you can see in my Test Method I have created two contact records and associated them with a new custom object record.  I've then created the Task and checked it's inserted.  However none of the test method works and it shows as 0% Coverage.

Any help or guidance would be really appreciated as I'm starting to go mad!!

Kev 

 

 

static testmethod void testCustomReferralTaskController() {
    Test.startTest();
    	//Create Referrer
    	VistageTestData data = new VistageTestData();
    	Account[] testAccounts = data.gimmeAccounts(2);
    	Contact testContact = data.gimmeContacts(testAccounts)[0];
    	Contact testContactDetails = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
    	testContactDetails.Staff__c = true;
    	update testContactDetails;
    
	//Create Referral
	VistageTestData data2 = new VistageTestData();
	Account[] testAccounts2 = data2.gimmeAccounts(2);
	Contact testContact2 = data2.gimmeContacts(testAccounts)[0];
	Contact testContactDetails2 = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
	testContactDetails2.Member__c = true;
	update testContactDetails2;    
    
	Referral__c Referral = new Referral__c(
        Referrer__c = testContactDetails.Id,
        Contact_Referral_Name__c = testContactDetails2.Id
		);
        insert Referral;
            
	Task testTask = new Task (
		WhoId = testContactDetails2.Id,
		WhatId = Referral.Id,
		Subject = 'Referral Validation',
		ActivityDate = date.today() + 7,
		ReminderDateTime = datetime.now() + 7,
		Description = 'Please Validate the Referral');
	insert testTask; 
    
   	Task t = [Select Id, whoid from Task where WhatId = :Referral.Id Limit 1];
   	system.assertEquals(t.whoid,testContactDetails2.Id);
   	Test.stopTest();
} 

 

 

Hi All,

 

I have written the below trigger to create a Task on the Account record when the field (OneSource__OSKeyID__c) is Null.

 

This works great (please be gentle as I'm still learning) and I have created a Test Trigger, however, there is one line of code that is stopping me from getting 100% coverage on this trigger.

 

The one line is this: 

 

    setAccount.add(objTask.WhatId);


If someone could help I would be very grateful.

 

Kev

 

Trigger

trigger AssignOneSourceTask on Account (after insert) 
{
     Set<Id> setAccount = new Set<Id>();
        for(Task objTask: [Select Id, WhatId from Task where WhatId In: trigger.new and Subject = 'OSKey ID Missing on Account'])
        setAccount.add(objTask.WhatId);
        List<Task> taskList = new List<Task>();
        for(integer i=0; i<trigger.new.size(); i++)
        {
            if(!setAccount.contains(trigger.new[i].Id))
                if (trigger.new[i].OneSource__OSKeyID__c == NULL) 
     {
     Task t = new Task(
     Subject = 'OSKey ID Missing on Account',
     WhatId = trigger.new[i].id,
     Description = 'Please update OSKey ID on Account Record',
     Priority = 'Normal',
     Status = 'Not Started',
     IsReminderSet = True,
     ReminderDateTime = System.now()+1,
     ActivityDate = Date.today()+2,
     OwnerId = '005E0000000YhNn');
     
     taskList.add(t);
     setAccount.add(trigger.new[i].Id);
     }
     }
 if(!taskList.isEmpty())
    insert taskList;
}

 

Test Trigger 

@isTest
public with sharing class TriggerTest_Account_OneSourceID {
	public static testmethod void testAccount_NoOneSourceID() {
		System.debug('VistageDebug: entering TriggerTest_Account_OneSourceID');
		//Create Test Account
		Account testAccounts = new Account(Name='ACCOUNT_NAME');
		Insert testAccounts;
		
		List<Task> taskList = [SELECT id, ActivityDate, subject from Task WHERE whatId = :testAccounts.id];
        System.assertEquals(1,taskList.size());     
		System.assertEquals('OSKey ID Missing on Account',taskList[0].Subject);
		
	}
	
}

 

Hi all,

 

Hopefully this is a simple one but I have a visualforce form which users use to load a lead, however, I want to populate a lookup field with the userid only when the user comes under a certain role.

 

I have tried this query to create the string

 

String userbasedid = [select ID from user where (userRoleid = '00EE0000000gXTj' AND id = :UserInfo.getUserId()].id;   

 

Piece of Form Code:

IdentifyUser = userbasedid

      

So the form works fine when the users role equals the above userroleid, however, as soon as a different user with a different user role uses it I get the error:

 

List has no rows for assignment to SObject.

 

So I need to figure a way that when the query result is null it doesn't try to populate the identifyuser field.

 

Thanks

Kev 

 

Hey All,


Sorry still trying to understand testmethods and hopefully someone can answer this pretty quickly.

 

I have a controller that does the below for a VF Page:

 

Public static  integer getUnQualified()
    {
    integer UnQualified = [SELECT count() FROM Lead where OwnerId =:UserInfo.getUserId() AND Status='Unqualified' AND IsConverted = False ];
    return UnQualified ;
    }

However how do I write a test method for this?

 

As far as I can understand I need to:

 

Start Test

Set Current Page

New Controller

Insert Lead with Status = Unqualifed

Check that Count returns result

Stop Test

 

My issue is I don't know how to test the count function.

 

Thanks in advance.


Kev

 

 

Hi All,

 

Hoping someone can help as I can't seem to figure this out.


I have a user profile which is set so Campaigns are read only which is correct, however, I want to stop this particular user profile from being able to add, edit or delete Campaign Members

 

The test user has marketing user field unticked in their profile as I thought that might have been the issue but that made no difference.


All I want is for this particular user profile to have a Read Only view of Campaigns and Read Only of the list of Campaign Members for that Campaign.

 

Thanks in advance for any help.

 

Kev

 

 

Hi All,

 

I have a simple form with a customer controller which I now need to create the test code so I can deploy to live system, however, I'm havig some issues creating the test method as I'm relatively new to testing.  So I'm hoping someone can help as I can't seem to find the answer anywhere.

 

The VisualForce Page is called New_Reserve_Entry.

 

And here is the Reserve Controller Code:

 

public with sharing class Reserve {
   
    public Lead lead {get; private set;}
   
    public String company {get; set;}
    public String email {get; set;}
    public String phone {get; set;}
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String title {get; set;}
    public string primary_campaign {get; set;}

    public String getName() {
        return 'Reserve';
    }

    // save button is clicked
    public PageReference save() {

        Lead l = new Lead(
        OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = firstName,
        LastName = lastName,
        Email = email,
        Phone = phone,
        Title = title,
        Company = company,
        );
       
      
    try {
      insert l; // inserts the new record into the database
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Error adding Candidate to Reserve List.'));
      return null;
    }
     
        return Page.New_Reserve_Entry_Confirmation;
}

}

@isTest
private with sharing class Reserve_Test {
	
 	public static testMethod void testReserve_Test() {
        PageReference pageRef = Page.New_Reserve_Entry;
        Test.setCurrentPage(pageRef);
      
        reserve controller = new reserve();
        String nextPage = controller.save().getUrl();
              

        //Controller and Data
        controller = new reserve(); 
        Lead l = new Lead(
        OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = 'FirstName',
        LastName = 'LastName',
        Email = 'test@test.com',
        Phone = '001',
        Title = 'Junior',
        Company = 'Acme'
        );

        //Save
        nextPage = controller.save().getUrl();


        // Verify
        Lead[] leads = [select id, email from lead where Company = 'Mystry'];
        System.assertEquals('firstlast@acme.com', leads[0].email);
        System.assertEquals('lastname',leads[0].LastName);
        
        
    }
		
}

 

So I understand that the test code must call the page, load the controller, insert the lead data, save, confirm return page and check data was inserted.  However, writing it is the problem:

 

I got this far and then got stuck:  Currently I get an error for string nextpage = controller.save().getUrl() saying "Attempt to de-reference a null object"



 

 

 

I would really appreciate if someone could help me out either by fixing the test code, showing me a test code they have for something similar or any links that could help.


Thanks

Kev

 

 

 

 

 

 

 

Hi All,

 

Has anyone been able to create a Visualforce Page that shows a table which has pagination (next and previous) and the ability to click a column name to sort? There seems to be lots of one or the other but not both at the same time.

 

I have created a table using the ApexPages.StandardSetController which has allowed me to do pagnination on the table but I can't seem to find a solution to sort by clicking the column name which works with the standardsetcontroller.

 

Any code examples or links to blogs that may help would be really appreciated.

Hi all,

 

I need to be able to show a list based on a soql query, however, I want it to display like a standard list view like the below image.  Rather than me trying to attempt it from scratch has anyone coded this in a Visualforce Page using css?

 

 

Thanks

Kev

Hi all,

 

I have a visualforce page that creates a new lead, however, how can I get it to add the new lead to a campaign, like a web-to-lead form does.  In a web-to-lead form you would use campaign_id and member_status but that doesn't work in the apex.  I also have a primary_campaign_id__c field in the lead so could I use that and if so how?

 

Here is the apex code:

 

public class Reserve {

    public Lead lead {get; private set;}

    public String company {get; set;} 
    public String email {get; set;}
    public String phone {get; set;}
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String title {get; set;}

    public String getName() {
        return 'Reserve';
    }

    // save button is clicked
    public PageReference save() {
        
        Lead l = new Lead(
        OwnerId = '00GE0000000hCBH',
        LeadSource = 'Reserve',
        FirstName = firstName,
        LastName = lastName,
        Email = email,
        Phone = phone,
        Title = title,
        Company = company,
        List_Assignment__c = 'Reserve',
        Primary_Campaign_ID__c = '701E0000000TwCG'
        );
        
       
    try {
      insert l; // inserts the new record into the database
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.Error,'Error adding Reserve List.'));
      return null;
    }
        return Page.confirmationReserveEntry;      
 
    } 
  
}

Thanks

Kev

Hi All,


I'm trying to find a solution for the following:

 

When the Campaign is set to Active it updates a custom field (CampaignField__c) in all Campaign Members for that Campaign.

 

I can't seem to find any examples when it comes to triggers with Campaigns.

 

I think the logic is:

  1. After Update
  2. Query CampaignMembers
  3. If Campaign ISActive = True
  4. Then CampaignField__c on CampaignMembers = True

Thanks

Kev 

Hi All.

 

I'm hoping someone can help with this simple fix.

 

I have the following code below that looks at a lead field called custom field hubspot_campaign_c (this has a campaign ID in) and if it is not null it adds the lead to the specific campaign listed in hubspot_campaign_c.

 

trigger LeadToCampaign on Lead (after update, after insert) {
 
for (Lead l: trigger.new) {

if (l.HubSpot_Campaign__c != null ) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; //You will have to know the ID or query for it or something
                cm.Status = 'Responded'; //Or whatever default status you want on the member
                
            insert cm;

}
}
}

 

This works perfectly fine but it generates an error if the lead record is updated because the lead will already exist in the campaign.

 

So what I need help on is to add a line which queries the campaignmembers and checks to see if the lead already exists for the campaignID listed in the custom field hubspot_campaign_c.

 

So what I was trying to do was create a list of campaign members where the leadID matches in the campaign member list but this is where I got stuck.  This will generate a list of campaigns the lead is in and I then need to filter it by campaignid = hubspot_campaign_c and then if campaignmember list is null add the campaign member.  

 

trigger LeadToCampaign on Lead (after update, after insert) {

List<Id> leads=new List<Id>();

for (Lead l: trigger.new) {

List<CampaignMember> cms=[Select LeadID, CampaignID FROM CampaignMember WHERE LeadID IN: leads];
        
if (l.HubSpot_Campaign__c != null) {
           CampaignMember cm = new CampaignMember();
                cm = new CampaignMember();
                cm.LeadId = l.Id;
                cm.CampaignId = l.HubSpot_Campaign__c; //You will have to know the ID or query for it or something
                cm.Status = 'Responded'; //Or whatever default status you want on the member
                
            insert cm;

}
}
}

 

Any help would be much appreciated.


Kev

Hey All,


Not sure what is going on here especially as it's a simple trigger.

 

As you can see the trigger flags an error if anyone other than a Systems Administrator tries to delete a Completed Task.

 

trigger trgr_Task_PreventDelete_bd on Task (Before delete) {

    for (Integer i = 0; i < Trigger.Old.size(); i++) {
        if (Trigger.Old[i].Status == 'Complete' && UserInfo.getProfileId() != '00eE0000000XjEM') {
               // Cannot delete this task
               Trigger.Old[i].addError('This task cannot be deleted because you are not assigned as the owner.  Please contact an administrator.');
        }
    }
}

 

So my logic was create a lead and task and then try to delete while running as a user other than a system admin but it doesn't work.

 

@isTest
private class test_trgr_PreventTaskDelete{
    public static testMethod void testDeleteFail()
    {
        User rep = [Select Profileid from User where Name = 'Test Chair' limit 1];
        System.runAs(rep)
        {
        System.debug('VistageDebug: entering TriggerTests_Campaign_ActiveCampaign_Before_Delete');
        
        Lead l2 = new Lead(OwnerID = '005E0000000YhNn',Status = 'New',Company = 'Test',LastName = 'Test',LeadSource = 'Advertising',Industry = 'Fitness');
        Insert l2;

    //Setup t2 and relate to L2
        Task t2 = new Task(OwnerID = '005E0000000YhNn',Subject = 'test',Type = 'Cold Call',Status = 'Not Started',Priority = 'Normal',WhoId = l2.id);
        insert t2;
    
    //Update t2
        Task updateMe = [SELECT Id FROM Task WHERE Id = :t2.Id];
        updateMe.Status = 'Completed';
        update updateMe;
        
        Task TaskDelete = [SELECT Id FROM Task WHERE Id = :t2.Id];
           try
               {
                delete TaskDelete;
                  // should throw an exception - the following assertion will cause an error if the code carries on
                  System.assert(false);
               }
               catch (DMLException e)
               {
               // expected - could assert the message here
               }
           }
        }
}

 

Any help would be highly appreciated as one moment I think I'm starting to understand things and then the next moment I hit another road block.

 

Thanks

Kevin 

Hi, 

 

I have an issue with the below code I'm developing.  It seems I get the error "System.FinalException: Record is read-only"

 

Looking at the debug code it is caused by line 18 - if( CampaignMemberParentCampaign.IsActive = True) 

 

Can anyone help as I haven't come across this before.

Thanks

Kev 

 

 

trigger CampaignMemberStatus on Campaign (after update) {
    for( Campaign currentNewCampaign : Trigger.new ) 
    {
      Campaign correspondingOldCampaign = Trigger.oldMap.get( currentNewCampaign.Id );
      
      //if( currentNewCampaign.Physical_Street__c != correspondingOldCampaign.Physical_Street__c) 
      //{
      //  currentNewCampaign.Physical_Street_prior__c = correspondingOldCampaign.Physical_Street__c;
      //}
    }

      CampaignMember[] CampaignMembersRelatedToCampaignBatch = [ select CampaignID, Campaign_Active_V2__c from CampaignMember
      where CampaignId in :Trigger.new ];

      for( CampaignMember currentCampaignMember : CampaignMembersRelatedToCampaignBatch ) 
      {
        Campaign CampaignMemberParentCampaign = Trigger.newMap.get( currentCampaignMember.CampaignID );
        if( CampaignMemberParentCampaign.IsActive = True) 
        {
        currentCampaignMember.Campaign_Active_V2__c = 'true';
        }
      }

    update CampaignMembersRelatedToCampaignBatch;
}

 

 

Hi All,


I'm trying to find a solution for the following:

 

When the Campaign is set to Active it updates a custom field (CampaignField__c) in all Campaign Members for that Campaign.

 

I can't seem to find any examples when it comes to triggers with Campaigns.

 

I think the logic is:

  1. After Update
  2. Query CampaignMembers
  3. If Campaign ISActive = True
  4. Then CampaignField__c on CampaignMembers = True

Thanks

Kev 

Hi all,

 

I have created Campaign Member number field (Campaign_Active__c) which is either 1(active) or -1(inactive) depending on whether the campaign is active.  This updates when the Campaign is changed from active to inactive.

I now need to create a trigger which adds or subtracts a score from the lead scoring field (Campaign_Score__c) depending on the Campaign_Active__c.

 

I did a search and found some code and tried modifying it but currently am not being very succesfully so an help would be appreciated.  

 

trigger CampaignMemberAfter on CampaignMember(after insert, after update, after delete)
{
    Map<Id,CampaignMember> campaignLeads = new Map<Id,CampaignMember>{};
    List<CampaignMember> camMembers = trigger.IsInsert || trigger.IsUpdate ? trigger.new : trigger.old;
    
    for(CampaignMember cm : camMembers)
        campaignLeads.put(cm.LeadId, cm);
 
    List<Lead> consToUpdate = new List<Lead>{};
 
    for(Lead con : [Select Id, Campaign_Score__c from Lead where Id in :campaignLeads.keySet()])
    {
        if(trigger.isInsert || trigger.isUpdate) 
        con.Campaign_Score__c += campaignLeads.get(con.Id).Campaign_Active__c;
 
        else if (trigger.isDelete)
        con.Campaign_Score__c += campaignLeads.get(con.Id).Campaign_Active__c;
 
        consToUpdate.add(con);
    }
}

 

 

 

Hey all,


Is it possible to create a field in the Lead fields that shows whether a lead is in any active campaigns or not?

 

For example: It doesn't matter if they are in one active campaign or three active campaigns it would shows as true and if no campaign it would be false.

 

Thanks

Kev 

Hi All,


I have the following query which I have tested and works in SoqlXplorer.

 

SELECT Member__c, (SELECT Joined_Date__c,Joined__c FROM Opportunities__r WHERE Joined_Date__c = LAST_N_DAYS:365) FROM Contact WHERE Member__c = TRUE LIMIT 1000

 

However, my issue is I want to count the results ie like the below but this query results in MALFORMED_QUERY: Grouped query cannot use child relationships in the SELECT list

 

SELECT Count(ID), (SELECT Joined_Date__c,Joined__c FROM Opportunities__r WHERE Joined_Date__c = LAST_N_DAYS:365) FROM Contact WHERE Member__c = TRUE LIMIT 1000

 

Can anyone help.


Thanks


Kev

 

Hi All,

 

Has anyone been able to create a Visualforce Page that shows a table which has pagination (next and previous) and the ability to click a column name to sort? There seems to be lots of one or the other but not both at the same time.

 

I have created a table using the ApexPages.StandardSetController which has allowed me to do pagnination on the table but I can't seem to find a solution to sort by clicking the column name which works with the standardsetcontroller.

 

Any code examples or links to blogs that may help would be really appreciated.