+ Start a Discussion
Sandra WicketSandra Wicket 
Hi Guys,

this is my code :
public class CreateMultiExtraBoost {

	public List<cBoost> boostList {get; set;}
    Integer listSize {get;set;}
    public Id opportunityId {get;set;}
    public ID finalBoostId {get; set;}
        
    // Constructor 
    public CreateMultiExtraBoost (){
    	opportunityId =  ApexPages.currentPage().getparameters().get('oppId');
    }

	//Methode
	public List<cBoost> getBoosts() {
		if(boostList == null) {
			boostList = new List<cBoost>();
			for(FinalBoost__c c: [select Id, Name from FinalBoost__c ]) {
				boostList.add(new cBoost(c));
			}
		}
		return boostList;
	}

	public PageReference save() {
 
		List<FinalBoost__c> selectedContacts = new List <FinalBoost__c>();
        List<BoostOpp__c> boostItems = new List <BoostOpp__c>(); 
        pagereference oppPage = new pagereference('/' + opportunityId);

		for(cBoost cCon: getBoosts ()) {
			if(cCon.selected == true ) {
				selectedContacts.add(cCon.con);
			}
		}

		System.debug('These are the selected ...');
		for(FinalBoost__c con: selectedContacts) {
			system.debug(con);
		}
        
        for (FinalBoost__c con: selectedContacts) {
            	boostItems.add(new BoostOpp__c());
            	finalBoostId = con.Id;
            
            		for(BoostOpp__c boostIteminList : boostItems) {
                        boostIteminList.Opportunity__c = opportunityId;
                        boostIteminList.FinalBoost__c = finalBoostId;
       	 }
       }
        insert boostItems;
        return oppPage;
	}
    
   
   // WrapperClass
	public class cBoost {
		public FinalBoost__c con {get; set;}
		public Boolean selected {get; set;}

		// Constructor 
        public cBoost(FinalBoost__c c) {
			con = c;
			selected = false;
		}
	}
}

A visualforcepage shows the table of FinalBoost records. I can select records and use them in the save methode.  The BoostOpp__c object is a junction object. It is related to the opportunity and the FinalBoost Object. 

In my loop, i want to create for each selected record one child record and assign the parent id (FinalBoost) to the masterDetail field. At the moment, it creates for each selection one record but allways with the same finalBoostId.  Is there a simple solution for that ? 


Cheers Sandra
Best Answer chosen by Sandra Wicket
Saket Sharma 30Saket Sharma 30
Hi Sandra,

Please find the solution below.
 
public PageReference save() {

List<FinalBoost__c> selectedContacts = new List <FinalBoost__c>();
List<BoostOpp__c> boostItems = new List <BoostOpp__c>(); 
pagereference oppPage = new pagereference('/' + opportunityId);

for(cBoost cCon: getBoosts ()) {
	if(cCon.selected == true ) {
		selectedContacts.add(cCon.con);
    }
}

for (FinalBoost__c con: selectedContacts) {
	
	BoostOpp__c boost = new BoostOpp__c();
    boost.FinalBoost__c = con.Id;
	boost.Opportunity__c = opportunityId;
	boostItems.add(boost);

	
}
insert boostItems;
return oppPage;
}

 
cyberdynebotcyberdynebot 
Fairly new to Apex and I have a trigger that checks if a Task is on a Contact and pulls in 2 fields from the Contact record that will update the Task. 

It works fine for one record at a time but when trying to bulk if there are multiple tasks for the same Contact it will only fire for the last Activity in the Trigger.new list and not all that share the same WhoId.

Looks like the Map is only capturing the Contact Id once and then the SOQL query only returns one result. Just need help figuring out the solution so that each Task will get updated with the Contact fields.
 
trigger TaskTrigger on Task (before insert, before update) {

    Map<Id, List<Task>> conIdsMap = new Map<Id, List<Task>>();

    for (Task t : Trigger.new) {
            //Search for Contact on Task
        if (t.whoid != null && t.whoid.getsObjectType().getDescribe().getName() == 'Contact') {
                    List<Task> temp = new List<Task>();
                    temp.add(t);
                    conIdsMap.put(t.whoid, temp);
        }
    }

    if (conIdsMap.size() > 0) {
            for(Contact con : [Select Id, Name, Status__c, Corp_Lead_Score__c from Contact where Id in :conIdsMap.keySet()]) {
                for(Task t :conIdsMap.get(con.Id)){
                    t.Stage__c = con.Status__c;
                    t.Corp_Lead_Score__c = con.Corp_Lead_Score__c;
                }
            }  
        }
}

 
Best Answer chosen by cyberdynebot
Alain CabonAlain Cabon
Hi,
 
    for (Task t : Trigger.new) {
        //Search for Contact on Task
        if (t.whoid != null && t.whoid.getsObjectType().getDescribe().getName() == 'Contact') {
            if (conIdsMap.containsKey(t.whoid)) {
                List<Task> temp = (List<Task>)conIdsMap.get(t.whoid);
                temp.add(t);
            } else {
                List<Task> temp = new List<Task>();
                temp.add(t);
                conIdsMap.put(t.whoid, temp);
            }          
        }
    }

 
IntegrationGuyIntegrationGuy 
global class PublicEmailPreferencesURLRewriter implements Site.UrlRewriter {
    public static final String EMAIL_PROFILE_FRIENDLY = '/profile/';
    public static final String EMAIL_PROFILE_VF_PAGE_BASE = '/PublicEmailPreferences';
    public static final String EMAIL_PROFILE_VF_PAGE = EMAIL_PROFILE_VF_PAGE_BASE + '?' + PublicEmailPreferencesController.URL_PARM_ID + '=';

    global PageReference[] generateUrlFor(PageReference[] urls) {
        
        System.debug('generateUrlFor has been invoked for ' + urls);
        PageReference[] pageRefs = new List<PageReference>();
        
        Set<Id> cIds = new Set<Id>();
        for (PageReference pRef : urls) {
            String urlStr = pRef.getUrl();
            if (urlStr.startsWith(EMAIL_PROFILE_VF_PAGE_BASE)) {
                cIds.add(urlStr.substring(EMAIL_PROFILE_VF_PAGE.length()));
            }
        }
        
        Map<Id, Contact> contactsById = new Map<Id, Contact>([SELECT Id, HashId__c FROM Contact WHERE Id IN :cIds]);
        for (PageReference pRef : urls) {
            String urlStr = pRef.getUrl();
            pageRefs.add(
                urlStr.startsWith(EMAIL_PROFILE_VF_PAGE_BASE) ?
                new PageReference(EMAIL_PROFILE_FRIENDLY + contactsById.get(urlStr.substring(EMAIL_PROFILE_VF_PAGE.length())).HashId__c) :
                pRef
            );
        }
         return pageRefs;
    }
    
    global PageReference mapRequestUrl(PageReference url) {
        
        PageReference pageRef = null;
        
        String urlStr = url.getUrl();
        System.debug('mapping url=' + urlStr);
        
        if (urlStr.startsWith(EMAIL_PROFILE_FRIENDLY)) {
            String hashId = urlStr.substring(EMAIL_PROFILE_FRIENDLY.length());
            if (hashId != '') {
                List<Contact> contacts = [SELECT Id FROM Contact WHERE HashId__c = :hashId];
                if (!contacts.isEmpty()) {
                    pageRef = new PageReference(EMAIL_PROFILE_VF_PAGE + contacts[0].Id);
                } else {
                    pageRef = new PageReference(EMAIL_PROFILE_VF_PAGE);
                }
            }
        }
        return pageRef; 
    }
}
Best Answer chosen by IntegrationGuy
IntegrationGuyIntegrationGuy

This test class worked like a charm :)
<pre>

@IsTest
public class PublicEmailPreferencesURLRewriter_T1{
  @testSetup
  static void setupTestData(){
    test.startTest();
    Contact contact_Obj = new Contact(LastName = 'LastName194', HasOptedOutOfEmail = false);
    Insert contact_Obj; 
    test.stopTest();
  }
  static testMethod void test_generateUrlFor_UseCase1(){
    List<Contact> contact_Obj  =  [SELECT LastName,HasOptedOutOfEmail from Contact];
    
    System.assertEquals(true,contact_Obj.size()>0);
    PublicEmailPreferencesURLRewriter obj01 = new PublicEmailPreferencesURLRewriter();
    obj01.generateUrlFor(new List<PageReference>());
  }

    static testMethod void test_generateUrlFor_UseCase3(){
    List<Contact> contact_Obj  =  [SELECT LastName,HasOptedOutOfEmail from Contact];
    System.assertEquals(true,contact_Obj.size()>0);
    PublicEmailPreferencesURLRewriter obj01 = new PublicEmailPreferencesURLRewriter();
    contact_Obj[0].LastName='test';
    contact_Obj[0].HasOptedOutOfEmail=false;
    Update contact_Obj[0];
    obj01.generateUrlFor(new List<PageReference>());
  }
  
  static testMethod void testURLrewriter()
     {     // I try to create the internal saleforce pageReference<br><br>      
         pageReference myPage = new pageReference('/apex/myPage');
       Test.setCurrentPage(myPage);
       myPage.setRedirect(true);
       List<PageReference> res = new List<PageReference>();
       res.add(myPage);
       res.add(new PageReference('/apex/myPage2' )); 
       // now call the methods<br><br>  
        PublicEmailPreferencesURLRewriter urlClass = new PublicEmailPreferencesURLRewriter ();
        urlClass.mapRequestUrl(myPage);
        urlClass.generateUrlFor(res);
    }
  

    static testMethod void test_mapRequestUrl_UseCase1(){
    PageReference pageRef = Page.PublicEmailPreferences;
    Test.setCurrentPage(pageRef);
    List<Contact> contact_Obj  =  [SELECT LastName,HasOptedOutOfEmail, HashId__c from Contact];
    System.assertEquals(true,contact_Obj.size()>0);
    ApexPages.StandardSetController sc = new ApexPages.StandardSetController(contact_Obj);
    PublicEmailPreferencesURLRewriter obj01 = new PublicEmailPreferencesURLRewriter();
    
    contact_Obj[0].LastName='test';
    contact_Obj[0].HasOptedOutOfEmail=false;
    Update contact_Obj[0];
    obj01.mapRequestUrl(new PageReference('/profile/generatesome random hash code'));
  }
  
  
   static testMethod void test_mapRequestUrl_UseCase2(){
    List<Contact> contact_Obj  =  [SELECT LastName,HasOptedOutOfEmail from Contact];
    System.assertEquals(true,contact_Obj.size()>0);
    PublicEmailPreferencesURLRewriter obj01 = new PublicEmailPreferencesURLRewriter();
    
    obj01.mapRequestUrl(new PageReference('https://fakesite.com'));
  }
  
}

</pre>

Daniel DlugosDaniel Dlugos 
I'm just learning the basics of Apex, and I could use a little help writing a test class for a basic trigger I have that prevents users from deleting tasks. I've been at this for over a week now, and I've just hit a wall with it.

Could anyone help me out with a test class for this? I'll be sure to make it best answer :)

Thanks in advance.
trigger NoDeleteOnTask on Task (before delete)
{
   
    if(trigger.isDelete){
        Set<Id> allowedProfileIds = new Set<Id>();
        for(Profile p :[SELECT Id FROM Profile WHERE (Name = 'System Administrator' )]){
            allowedProfileIds.add(p.Id);
        }

        for (Task a : Trigger.old){
            if(!allowedProfileIds.contains(UserInfo.getProfileId())){
                a.addError('Task\'s can\'t be deleted. Please contact the system administrator if you require further assistance.');
            }
        }
    }
}

 
Best Answer chosen by Daniel Dlugos
Abdul KhatriAbdul Khatri
Here you go. Please mark the best answer if helped
 
@isTest
public class NoDeleteOnTask_Test {  
    @testSetup static void setupTestData() {
		Id adminProfId = [Select id from Profile WHERE Name=:'System Administrator'].Id;
        User adminUser = new User();
        adminUser.FirstName = 'Admin';
        adminUser.LastName = 'testUser';
        adminUser.Email = 'AdmintestUserak@test.com';
        adminUser.Username = 'AdmintestUserak@test.com';
        adminUser.ProfileId = adminProfId;
        adminUser.IsActive = true;
        adminUser.LanguageLocaleKey = 'en_US';
        adminUser.LocaleSidKey = 'en_US';
        adminUser.Alias = adminUser.FirstName.substring(0,1) + adminUser.LastName.substring(0,4);
        adminUser.EmailEncodingKey = 'UTF-8';
        adminUser.TimeZoneSidKey = 'GMT';        
        insert adminUser;

		Id stdProfId = [Select id from Profile WHERE Name=:'Standard User'].Id;
        User stdUser = new User();
        stdUser.FirstName = 'Admin';
        stdUser.LastName = 'testUser';
        stdUser.Email = 'stdtestUserak@test.com';
        stdUser.Username = 'stdtestUserak@test.com';
        stdUser.ProfileId = stdProfId;
        stdUser.IsActive = true;
        stdUser.LanguageLocaleKey = 'en_US';
        stdUser.LocaleSidKey = 'en_US';
        stdUser.Alias = stdUser.FirstName.substring(0,1) + stdUser.LastName.substring(0,4);
        stdUser.EmailEncodingKey = 'UTF-8';
        stdUser.TimeZoneSidKey = 'GMT';        
        insert stdUser;
       
        Task taskData = new Task(Priority = 'Normal',Subject = 'Test',Status = 'Scheduled', OwnerId = stdUser.Id);
        insert taskData;
        
    }
    
    static testMethod void test_admin_must_be_able_to_delete_task(){
     	User adminUser = [SELECT Id FROM User WHERE Username = 'AdmintestUserak@test.com'];
        Task taskData = [SELECT Id FROM Task Where Subject = 'Test' LIMIT 1];
        
        System.runAs(adminUser)
        {    
            delete taskData;
        }
        
        try{
        	taskData = [SELECT Id FROM Task Where Subject = 'Test' LIMIT 1];
        }catch(Exception ex){
            system.assert(true);
        }       
        
    }   
    
    static testMethod void test_user_must_not_be_able_to_delete_task(){
     	User stdUser = [SELECT Id FROM User WHERE Username = 'stdtestUserak@test.com'];
        Task taskData = [SELECT Id FROM Task Where Subject = 'Test' LIMIT 1];
        
        System.runAs(stdUser)
        {   
            try {
            	delete taskData;
            }catch(Exception ex){
                system.debug('ex : ' + ex.getMessage());
                system.assert(ex.getMessage().contains('Task\'s can\'t be deleted'));
            }
        }       
    }     
}

 
shakila Gshakila G 
I have 5 mobile fields in lead object
To avoid the lead duplicate I have to check all the 5 fields with each other

This my code is trying to check the duplicates. Is the correct way to check the duplicates?

Trigger leadduplicatecheck on lead(before insert,Before Update)
{

List<Lead> llist=new list<lead>();

Set<string> setMobilePhone =new set<String>();
Set<string> setWhatsapp =new set<String>();
Set<string> setMobile =new set<String>();
Set<string> setPhone     =new set<String>();
Set<string> setPhoneAdd =new set<String>();

for(Lead l:Trigger.new)
{
setMobilePhone.add(l.MobilePhone);
setWhatsapp.add.(l.Whatsapp_Mobile__c);
setMobile.add.(l.Mobile_Additional__c);
setPhone.add.(l.Phone);
setPhoneAdd.add.(l.Phone_Additional__c);

}

llist=[select ID from Lead where (MobilePhone =:setMobilePhone or MobilePhone=:setWhatsapp
MobilePhone =:setMobile or
MobilePhone =:setPhone or
MobilePhone =:setPhoneAdd  ) OR

(Phone =:setMobilePhone or
 Phone=:setWhatsapp or
Phone =:setPhone or
Phone =:setMobile or
Phone =:setPhoneAdd ) OR


(Mobile_Additional__c =:setMobilePhone or
 Mobile_Additional__c=:setWhatsapp or
Mobile_Additional__c =:setPhone or
Mobile_Additional__c =:setMobile or
Mobile_Additional__c =:setPhoneAdd ) OR

(Whatsapp_Mobile__c =:setMobilePhone or
 Whatsapp_Mobile__c=:setWhatsapp or
Whatsapp_Mobile__c =:setPhone or
Whatsapp_Mobile__c =:setMobile or
Whatsapp_Mobile__c =:setPhoneAdd ) OR

(Phone_Additional__c =:setMobilePhone or
 Phone_Additional__c=:setWhatsapp or
Phone_Additional__c =:setPhone or
Phone_Additional__c =:setMobile or
Phone_Additional__c =:setPhoneAdd )];



For(Lead l : Trigger.New)
{
if(Trigger.isupdate &&llist.size()>0)
{
l.adderror('Already Lead Exist with this Mobile Nuber, Duplicate');

}

if(Trigger.insert  && llist.size()>0)
{
l.adderror('Already Lead Exist with this Mobile Nuber');

}
}   
}


 
Best Answer chosen by shakila G
Om PrakashOm Prakash
Hi Shakila,
I suggest to use only one Set to add all numbers then query will be also simplify 
Padmanabhan KamuniPadmanabhan Kamuni 
Hey Folks,
I have a button in Community & I need some custom button action to be performed(not standard action).
Any help is appreciated.
For reference- https://paddycomm-developer-edition.ap5.force.com/forums/s/
more details- when a user click the Download button some custom action should be performed.currently new account is created (which I don't want).
Kindly help me on this.
Best Answer chosen by Padmanabhan Kamuni
Padmanabhan KamuniPadmanabhan Kamuni
Hi Selva,

Thank you for your reply. 
I got the solution, for this we need to install a button package (https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000EA6PTUA1)

Thank you!!. 
Michael Hedrick 2Michael Hedrick 2 
Hello All,
I have created an email service that allows the user to send an email from the Lead object in Salesforce and have the replied email be attched to the Lead record as a Task. 
The issue is that if the Customer does not select "Reply All" the replied to email will not get associated back to the Lead record because the email service email address is being added to the email and is not hte default from email address. 
So is there a way to make Email Service Email Address selectable?  Or can the Email Service Email Address be an organizational wide email address? 
Thanks,
M
  
Best Answer chosen by Michael Hedrick 2
Om PrakashOm Prakash
Please add your  Email Service Email Address in organizational wide email addres.
You need to debug myPlainText in code after line number 13 then you can verify that email service after copy verification link from debug log.
During sending you will send from number as Email service Address then reply will auto route and above code will work.
Vetriselvan ManoharanVetriselvan Manoharan 
Hi,
I need to add discount to line item dynamically. For eg: If a customer orders mac + iphone it should add 10% discount, mac + samssung 15% discount, again mac + iphone + samsung 25% should get added. It should check for all possible products and its discount. Can anyone help me with it? 

Thanks,
Vetri
Best Answer chosen by Vetriselvan Manoharan
Anupam RastogiAnupam Rastogi
Hi Vetri,

The requirement is not straight forward and would require customizations. I will help you with the design, and then may be you can start building the required objects etc.

Design Approach - 
1. Custom Object (Product Discounts) - Create a new object that stores all possible combinations of products that can exist for an opportunity with the respective discounts. Use a multi-select picklist field for storing the Product Combinations.
2. On Creating a new Line Item record a piece of code should do the following - 
       - Query the Custom object with the product combination present on the respective opportunity including this newly created Product
       - If the query returns a record then use the discount value mentioned in that record and update the opportunity Total Discount field
Example: If an Opportunity already has two line items with Products A and B respectively. When the user creates another line item with Product = C, the code should check if the Custom Object contains a record with the combination of A, B and C. If yes then the respective discount value should be used to update the Total Discount field on Opportunity.

Approach for checking Product Combination - 
1. Use a multi-select picklist field for storing the Product Combinations and another field to store the discounts.
2. When a new line item is created, create a string containing all the Products for that opportunity delimited with a semicolon ';'
3. This should return a single record of the Custom Object that matches the same combination of Products
4. Use the discount value of the retrieved record and update the Total Discount field of Opportunity

Point to Consider - 
You can choose between a Trigger and the new Process Builder for invoking this piece of code when a new line item record is created.

Sample lines of code to compare the combination of products with the Custom Object - 

//--- For Loop that traverses all the line item records for an opportunity and creates a ; delimited string of all Products
For (OpportunityLineItem oLI : [select Product2 from OpportunityLineItem 
                                where OpportunityId = :ParentId]) {
     //--- Declare ProductList as a String outside this For Loop
     if (ProductList == '')
         ProductList = oLI.Product2;
     else
         ProductList = ProductList + ';' + oLI.Product2;
}

//--- Product_Discounts__c is the new Custom Object created to hold the discount information
//--- MultiSelect_1__c is the multi select picklist
//--- Discount__c is the field to hold the Discount for the Product Combination
//--- This query checks the combination of line items with the Custom Object records. The order of Products in ProductList can be different than MultiSelect_1__c, it does not matter.
List<Product_Discounts__c> pDis = [select Id, MultiSelect_1__c, Discount__c from Product_Discounts__c 
                     where MultiSelect_1__c = :ProductList];

if(pDis.size() > 0)
	System.debug('Found a record with Discount equal to ' + pDis[0].Discount__c);

I have tried to be elaborative in explanation. I hope this solves your problem.

Thanks
AR

If you find this reply useful that solves your problem then please mark it as best answer.
 
Abhilash DaslalAbhilash Daslal 
I want to use 2 constructors within my Controller class, one for a VF component and another for VF page.is it possible to have the same SOQL within 2 constructors.Please give an example
Best Answer chosen by Abhilash Daslal
karthikeyan perumalkarthikeyan perumal
Hello

kindly consider this example 

Class: 
 
public with sharing class C {
    public C() {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Zero-constructor called'));
    }
    public C(C controller) {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Single-argument C called'));
    }
}


If your page written like this:
<apex:page controller="wrapperAccountOpportunity" ...

Then the zero-parameter constructor will be called.

If your page is written like this:
<apex:page standardController="Account" extensions="wrapperAccountOpportunity" ...

Then the constructor with the single parameter ApexPages.StandardController will be called.
If you want to call fetchQuery  from both constructors, you'll have to call it from both constructors. Only one constructor will ever be called per controller or extension.


And, given the following page:
 
<apex:page controller="C" extensions="C">
    <apex:messages />
</apex:page>
You may expect both constructors to be called, but instead, you'll find only the zero-length (default) constructor is called, since the class is referenced twice. In this sense, classes that become controllers are actually singletons in Visualforce. The controller version of the class is only instantiated once; it can still be constructed normally multiple times within the code itself, but Visualforce will only instantiate one automatically.


Hope its clear.


 
OnurKOnurK 

Hi All,

 

Can anyone please explain me the difference between List and Array. 

 

Test__c[] t = new Test__c[0];

vs

List<Test__c> t = new List<Test__c>();

 

Thanks 

Best Answer chosen by Admin (Salesforce Developers) 
Starz26Starz26
List can be multidimensional

A "array notation" of a list using [] can only be one dimensional