+ 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
Yup u r correct :)
Now please mark my answer as best answer :P
Justin LargeyJustin Largey 
Hi,

Are there any best practices when it comes to setting up version control (VC) in conjuction with using the Force.com IDE?

For example, should I make one big project in the Force.com IDE that contains all the meta data on my site and commit that?  Then any new classes or triggers should be a part of this project, and committed to VC?  Would this mean that for every feature I deploy, the entire site would be deployed, instead of just the changes I made?  

I'm curious what everyone else is doing.

Thanks




Best Answer chosen by Justin Largey
pconpcon
I just recently wrote a blog post about this [1].  I would maintian a repository that contains ALL of your code and configuration and then deploy that to your development sandbox.  From your develpment sandbox you can then choose to deploy only parts with changesets or using the IDE to do a full deploy back to your production instance.  While the post talks about git from the command-line, you could use git from within the IDE with one of the extensions for it.

[1] http://blog.deadlypenguin.com/blog/2014/07/21/using-git-with-salesforce-and-distributed-teams/
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);
            }          
        }
    }

 
sayanasreekanth@gmail.comsayanasreekanth@gmail.com 

Hi All

 

I am getting this error when i write the ontabenter function on the tab.

<apex:tab label="Billing" name="billName" id="tabBilling" ontabenter="callCon('Billing');" style="background-color:white;"  rendered="{!IF(strSearchlevel='1',false,true)}">

<apex:outputText value="{!IF(lstDisputeInfo.size>0,'Yes','No')}" label="Account In Dispute" />

 <apex:actionFunction name="callCon" oncomplete="callCon1();">
                        <apex:param name="firstParam" value="" assignTo="{!Tabselected}"/>
                        </apex:actionFunction>

 

Below is the error. when i remove the ontabenter action it is not throwing the error, but i need to write the ontabenter action in order to capture the clicks on the tab. Please let me know your taughts on this.Appreciate your time and help.

 

The value 'null' is not valid for operator '>'

Error is in expression '{!IF(lstDisputeInfo.size>0,'Yes','No')}' in component <apex:outputText> in page summarypage

 

Best Answer chosen by Admin (Salesforce Developers) 
kiran_mutturukiran_mutturu

try this

 

<apex:outputText value="{!IF(AND(NOT(ISBLANK(lstDisputeInfo)),lstDisputeInfo.size>0),'Yes','No')}" label="Account In Dispute" />

Vatsal GorVatsal Gor 
I have done the exact same thing as they have said in the module. But some how I am getting error like this: 
Challenge Not yet complete... here's what's wrong: 
Can't find the forceContent:fileUpload Lightning component in the 'New Lead' flow. Make sure the field’s unique name is 'Upload_File'
Though I have named the field as 'Upload_File'!!!

I am attaching the screen shot of how I have done it below..
My flow is also active and is also inclued in the page named "Process Automation Home". I don't know what is wrong. Kindly help me. 

User-added imageUser-added image
User-added image
Best Answer chosen by Vatsal Gor
Chris DuarteChris Duarte
I am sorry about this. We discovered that the challenge checker is looking for the second screen name to be Upload_Files (with an s on the end) rather than the lightning component being called Upload_File. We're getting it fixed. In the meantime, if you change the second screen name unique name to Upload_Files, you should be able to get through it.

We made a knowledge article on this (see below). My apologies again. 

https://force.desk.com/customer/portal/articles/2932027-lightning-flow-workaround-for-challenge-guide-users-through-your-business-processes-with-cloud-flow-designer?b_id=13478
Best Answer chosen by Marshall Priest
Ashlie Miller 8Ashlie Miller 8
Looks like you need to go back and do this module first:
https://trailhead.salesforce.com/modules/platform_dev_basics/units/platform_dev_basics_intro

It will then import the data that we're missing.  For some reason though it still didn't create the users Angela Agent or Randy Realtor so you will just need to create those manually then go back and add them to the chatter stream. 

I wish they would add a notice to this module that will inform people to do that first. Good luck :)
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>

Karna_ShivaKarna_Shiva 
 public class soapSforceComSchemasClassAccountins {
 public class SessionHeader_element {
        public String x00D90000000y0lh_AQ0AQGIsi542TCnp_73StsP8nawV5_7uVrHfVM0SyclcA_h1XKIVMRIiQAFjveUkYoo0HcVFXVHV1J6vjgM92eC2mdTmQCWQ;
        private String[] x00D90000000y0lh_AQ0AQGIsi542TCnp_73StsP8nawV5_7uVrHfVM0SyclcA_h1XKIVMRIiQAFjveUkYoo0HcVFXVHV1J6vjgM92eC2mdTmQCWQ_type_info = new String[]{'00D90000000y0lh!AQ0AQGIsi542TCnp.73StsP8nawV5.7uVrHfVM0SyclcA.h1XKIVMRIiQAFjveUkYoo0HcVFXVHV1J6vjgM92eC2mdTmQCWQ','http://soap.sforce.com/schemas/class/AccountInsert',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountInsert','true','false'};
        private String[] field_order_type_info = new String[]{'x00D90000000y0lh_AQ0AQGIsi542TCnp_73StsP8nawV5_7uVrHfVM0SyclcA_h1XKIVMRIiQAFjveUkYoo0HcVFXVHV1J6vjgM92eC2mdTmQCWQ'};
    }
    public class DebuggingInfo_element {
        public String debugLog;
        private String[] debugLog_type_info = new String[]{'debugLog','http://soap.sforce.com/schemas/class/AccountInsert',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountInsert','true','false'};
        private String[] field_order_type_info = new String[]{'debugLog'};
    }
    public class AccountInsert {
        public String endpoint_x = 'https://ap1.salesforce.com/services/Soap/class/AccountInsert';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public soapSforceComSchemasClassAccountins.SessionHeader_element SessionHeader;
        public soapSforceComSchemasClassAccountins.DebuggingInfo_element DebuggingInfo;
        public soapSforceComSchemasClassAccountins.CallOptions_element CallOptions;
        public soapSforceComSchemasClassAccountins.DebuggingHeader_element DebuggingHeader;
        public soapSforceComSchemasClassAccountins.AllowFieldTruncationHeader_element AllowFieldTruncationHeader;
        private String SessionHeader_hns = 'SessionHeader=http://soap.sforce.com/schemas/class/AccountInsert';
        private String DebuggingInfo_hns = 'DebuggingInfo=http://soap.sforce.com/schemas/class/AccountInsert';
        private String CallOptions_hns = 'CallOptions=http://soap.sforce.com/schemas/class/AccountInsert';
        private String DebuggingHeader_hns = 'DebuggingHeader=http://soap.sforce.com/schemas/class/AccountInsert';
        private String AllowFieldTruncationHeader_hns = 'AllowFieldTruncationHeader=http://soap.sforce.com/schemas/class/AccountInsert';
        private String[] ns_map_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountInsert', 'soapSforceComSchemasClassAccountins'};
        public void opportunityUpdate(String Name,String AccountNumber,String Description) {
            soapSforceComSchemasClassAccountins.opportunityUpdate_element request_x = new soapSforceComSchemasClassAccountins.opportunityUpdate_element();
            request_x.Name = Name;
            request_x.AccountNumber = AccountNumber;
            request_x.Description = Description;
            soapSforceComSchemasClassAccountins.opportunityUpdateResponse_element response_x;
            Map<String, soapSforceComSchemasClassAccountins.opportunityUpdateResponse_element> response_map_x = new Map<String, soapSforceComSchemasClassAccountins.opportunityUpdateResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://soap.sforce.com/schemas/class/AccountInsert',
              'opportunityUpdate',
              'http://soap.sforce.com/schemas/class/AccountInsert',
              'opportunityUpdateResponse',
              'soapSforceComSchemasClassAccountins.opportunityUpdateResponse_element'}
            );
            response_x = response_map_x.get('response_x');
        }
}

}
executing through Developer Console from other Salesforce Org:::

soapSforceComSchemasClassAccountins.AccountInsert a = new soapSforceComSchemasClassAccountins.AccountInsert();
a.opportunityUpdate('Microsoft','21232','Cognizant');

Line: 111, Column: 1
System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: 

INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session faultcode=sf:INVALID_SESSION_ID faultactor=
Best Answer chosen by Karna_Shiva
Karna_ShivaKarna_Shiva
I am able to insert account data from one salesforce org to another salesforce org.

partnerSoapSforceCom.Soap myPartnerSoap = new partnerSoapSforceCom.Soap(); 
partnerSoapSforceCom.LoginResult partnerLoginResult = myPartnerSoap.login('karnashiva@cognizant.com.dev', 'Password123'); 
soapSforceComSchemasClassAccountins.SessionHeader_element webserviceSessionHeader = new soapSforceComSchemasClassAccountins.SessionHeader_element(); 
webserviceSessionHeader.sessionId = partnerLoginResult.sessionId; 
soapSforceComSchemasClassAccountins.AccountInsert  myWebservice = new soapSforceComSchemasClassAccountins.AccountInsert();
myWebservice.SessionHeader = webserviceSessionHeader; 
myWebservice.opportunityUpdate('Sriram','1232323232323','Descriptiopn');
Greg Jankowski 14Greg Jankowski 14 
Get Started with Service Cloud

I am trying to add a Case Team Role, but cannot find it in my trailheard org.

any ideas?
Best Answer chosen by Greg Jankowski 14
Greg Jankowski 14Greg Jankowski 14
I see the issue. I had to switch to salesforce classic.
:(
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'));
            }
        }       
    }     
}