• Damien_
  • SMARTIE
  • 1977 Points
  • Member since 2011

  • Chatter
    Feed
  • 77
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 28
    Questions
  • 419
    Replies

I am trying to make a custom page in my Customer Portal that shows ALL the cases of an account instead of just that specific user's. 

 

The SQL statement I am using in my VisualForce page to do this is:

 

    SELECT CaseNumber, AccountId, Subject FROM Case WHERE AccounttId = {!$User.AccountId}

 

However, I get this error:

 

    Error: Field AccountId does not exist. Check spelling 

 

How would I create this custom page that shows all cases?

  • September 25, 2012
  • Like
  • 0
trigger CaseCloseTrigger on Case (after update){
        for(Case c : [SELECT id, Status FROM Case WHERE id in:trigger.new and Case.RecordTypeId = '0123000000001l1']){           
    if(c.Status == 'Completed' || c.Status == 'Closed'){                       
for(Training_Information__c customobj :
[Select Id, Status__c From Training_Information__c Where Case__c in: Trigger.newMap.keySet()]){
if(customobj.Status__c == 'Pending' || customobj.Status__c == 'Scheduled'){ trigger.new[0].addError('Training has not been Completed.');
}} } }}

 

Hi, I wanted to Query as 

 

Consider there are more than  50000 records in lead in production.

 

[SELECT Count(id) from Lead Limit 1]

 

Idealy it Returns only one record.

as i understand as in docs its mentioned it will throw an Too many rows Exception. 

 

SO how can i avoid this Exception. Or Batch Apex is the only solution for this. 

  • September 13, 2012
  • Like
  • 0

HI, this is my first trigger. Kindly tell me what mistake am doing?

 

1. The problem is : Every time this trigger is executed the record gets inserted twice...

 

How to stop this?

 

Please find the code below:

trigger SalesOrder on Sales_Order__c (after update){

    List <Sales_Order_Status_History__c> sosh = new List<Sales_Order_Status_History__c>();
    if(Trigger.isafter){
        for(Sales_Order__c  so : Trigger.new){
            if(so.Sales_Order_Status__c == 'Order Acknowledgement'){
                sosh.add(new Sales_Order_Status_History__c(Status__c = so.Sales_Order_Status__c, SO_No__c = so.Name,Record_Created_Date__c=so.createdDate,Last_Modified_Date__c=so.systemModStamp,Record_User__c=userinfo.getUserName()));   
                insert sosh;     
            }
            else if(so.Sales_Order_Status__c == 'Customer Inputs'){
                sosh.add(new Sales_Order_Status_History__c(Status__c = so.Sales_Order_Status__c, SO_No__c = so.Name,Record_Created_Date__c=so.createdDate,Last_Modified_Date__c=so.systemModStamp,Record_User__c=userinfo.getUserName()));   
                insert sosh;
            }
            else if(so.Sales_Order_Status__c == 'Scheduling'){
                sosh.add(new Sales_Order_Status_History__c(Status__c = so.Sales_Order_Status__c, SO_No__c = so.Name,Record_Created_Date__c=so.createdDate,Last_Modified_Date__c=so.systemModStamp,Record_User__c=userinfo.getUserName()));   
                insert sosh;
            }

}}}

Please help

Hi,

 

I got an error when executing the test method I wrote for a trigger. I saw many entries in the discussion boards about this, but no concrete answer and nothing I can make an abstraction and apply it to my problem.

 

 

I have a trigger where I create posts to a a specific group if the Opportunity is closed. The trigger looks like this:

 

trigger chatterUpdateTrigger on Opportunity (before update) {
	
	Id parentPostId = [SELECT Id 
					   FROM CollaborationGroup 
					   WHERE Name=:'All Group'].Id;
					   
	Id RecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Opportunity' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id RecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Opportunity' 
						AND DeveloperName=:'Record Type 2'].Id;
	
	List<FeedPost> listPosts = new List<FeedPost>();
	
    for (Opportunity opp: Trigger.new){
    	
    	//List<RecordType> listOppRecordTypes = [SELECT DeveloperName FROM RecordType WHERE Id=:opp.RecordTypeId AND DeveloperName=:'Record Type 2' AND DeveloperName=:'Record Type 2'];
    	Opportunity beforeUpdate = System.Trigger.oldMap.get(opp.Id);

    		if(opp.RecordTypeId == RecordType1){
    			
    			if(beforeUpdate.StageName != opp.StageName && opp.StageName=='We WON!'){
    				
    				FeedPost post = new FeedPost(ParentId= parentPostId,Body='The opportunity ' +beforeUpdate.Name+ ' with a value of '+beforeUpdate.Amount+'€ has been won!');            
	        		listPosts.add(post);
	        		
    			}
    		}else{
    			
    			if(opp.RecordTypeId == RecordType2){
			
					if(beforeUpdate.StageName != opp.StageName && opp.StageName=='We WON!'){
	    				
	    				FeedPost post = new FeedPost(ParentId=parentPostId,Body='The opportunity ' +beforeUpdate.Name+ ' with a value of '+beforeUpdate.Amount_Quotation_Price__c+'€ has been won!');            
		    			listPosts.add(post);
		        		
    				}
			
    			}
    		} 
	}
	
	try{
		
		insert listPosts;
		
	}catch(Exception ex){
		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'customer.service@myself.me'});
        mail.setSubject('Chatter Trigger ERROR');
        String body = 'This message was sent automatically from chatterUpdateTrigger from SF. \n'+
        'Apparently there was an error on the insertion of the Chatter Message. This is the exception: \n'+ex;  
        mail.setPlainTextBody(body);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
	
}

 

And this is the test class:

 

@IsTest
 public class testChatterUpdateTrigger{
    
    static testMethod void testChatterUpdateTrigger(){

	
	
	Id RecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Account' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id RecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Account' 
						AND DeveloperName=:'Record Type 2'].Id;

							
						
	Account ac1 = new Account(RecordTypeId = RecordType1,
							  Name = 'Test Account 1',
							  CurrencyIsoCode = 'EUR',
							  Industry = 'Test',
							  Account_Type__c = 'Agent',
							  BillingCountry = 'UK',
							  BillingCity = 'London',
							  BillingStreet = 'Aleski 123');
	insert ac1;
	
	Account ac2 = new Account(RecordTypeId = RecordType2,
							  Name = 'Test Account 2',
							  CurrencyIsoCode = 'EUR',
							  Industry = 'Test',
							  Account_Type__c = 'Agent',
							  BillingCountry = 'UK',
							  BillingCity = 'London',
							  BillingStreet = 'Aleski 123');
	
	insert ac2;							  
							  	
	
	Account account1= [SELECT Id,
									 Name
							  FROM Account
							  WHERE Name =: 'Test Account 1'
							  LIMIT 1];

	Account account2= [SELECT Id,
								 Name
							  FROM Account
							  WHERE Name =: 'Test Account 2'
							  LIMIT 1];

	Id oppRecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Opportunity' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id oppRecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Opportunity' 
						AND DeveloperName=:'Record Type 2'].Id;								  							  
	
	Opportunity oppRecType1= new Opportunity(RecordTypeId = oppRecordType1,
											 Name = 'Test 1',
											 AccountId = account1.Id,
											 CurrencyIsoCode = 'EUR',
											 Amount = 100,
											 CloseDate = system.today(),
											 StageName = 'Pre-Study');

	insert oppRecType1;
	
	Opportunity opRec1= [SELECT StageName
						   FROM Opportunity
						   WHERE Name =:'Test 1'
						   LIMIT 1];

	Opportunity oppRecType2= new Opportunity(RecordTypeId = oppRecordType2,
										 Name = 'Test 2',
										 AccountId = account2.Id,
										 End_Customer_Country__c = 'UK',
										 Industry__c = 'Auto',
										 CurrencyIsoCode = 'EUR',
										 Vehicle_Types_pick_several__c = 'Test',
										 No_of_Vehicles__c = 0,
										 Load_weight__c = 0,
										 Lifting_height_mm__c = 0,
										 Operating_Conditions__c = 'Outside',
										 Quotation_Price__c = 1000,
										 Scope__c = 'Other',
										 StageName = 'Pre-Study',
										 Quotation_valid_until__c = system.today(),
										 CloseDate = system.today(),
										 Navigation__c = 'Other');

	insert oppRecType2;
	
	Opportunity opRec2= [SELECT StageName
						  FROM Opportunity
						  WHERE Name = 'Test 2'
						  LIMIT 1];

	List<Opportunity> listOpp = new List<Opportunity>();
	listOpp.add(opRec1);
	listOpp.add(opRec2);
	
	Integer feedEntriesBefore = [SELECT COUNT() 
					   FROM CollaborationGroup 
					   WHERE Name=:'All Group'];

	test.startTest();					   

	oppKoti.StageName = 'We WON!';
	update opRec1;
	
	AGVopp.StageName = 'We WON!';
	update opRec2;
	
    Integer feedEntriesAfter = [SELECT COUNT()
						   		FROM CollaborationGroup
						   		WHERE Name=:'All Group'];

	system.assertNotEquals(feedEntriesBefore, feedEntriesAfter);
	
	test.stopTest();

	}
	
}

 And I got this error when executing tests:

 

System.DmlException: Update failed. First exception on row ' with id XXXXXXXXXXXXX: first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, chatterUpdateTrigger: excecution of BeforeUpdate ON LINE 115 -> that is the update of opRec1 in the test method.

 

Does anyone know exactly what is happening and why?

I need to add a record to a custom object after I insert a record into another custom object.  I have the trigger working for a straight forward insert, but I don't want to insert the record if a record already exists with that customer number.  Here is the code for my existing trigger.  The matching field in both custom objects is JDE_Cust__c; 

 

trigger GetAcctIdTrigger on Sales_History__c (after insert) {
    list <sales_history_comp__c> newshc = new list<sales_history_comp__c>();
    for (Sales_History__c sh : Trigger.new){
    system.debug('GeT SH = ' + sh);
       
    sales_history_comp__c ishc = new sales_History_Comp__c(); 
     ishc.Account__c = sh.Customer__c;
     ishc.JDE_Cust__c = sh.JDE_Cust__c;
     ishc.Customer_Name__c = sh.Cust_Name__c;
     ishc.Sales_History__c = sh.id;
     ishc.Comp_Year_1__c = sh.sales_Year__c;
     ishc.Comp_Year_2__c = '0000';
   system.debug('ISHC RECORDS = ' +ishc);    
     newshc.add(ishc);
      }
insert newshc;     
        }

  • August 20, 2012
  • Like
  • 0

So I've just started to work on an app that I wrote a year ago, which was using the api version 22. I havent touched this app in quite sometime, but we are now wanting to use it and there are some modifications that I need to make. I ran my tests and got 76% coverage. Well I thought it maybe a good idea to update the api version from 22 to the latest at 25. 

 

Heres what I get. I can update all classes and triggers except test class to 25 with no problems. When I update my test class to api version 24 or above I get:

 

4 errors of:

 

System.NullPointerException: Attempt to de-reference a null object

 

Stack traces for each of the above errors are:

Class.aiMatch.aimatchEditSettingsController.getApiUrlValue: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testEditSettingsControllerPos: line 106, column 1

 

 

Class.aiMatch.aimatchXmlApiCall.buildWebServiceRequest: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testXmlApiCall: line 44, column 1

 

Class.aiMatch.aimatchGetAdvertisersXmlApiCall.buildWebServiceRequest: line 17, column 1 Class.aiMatch.testaimatchOpportunityGrab.testGetAdvertisersXmlApiCall: line 63, column 1

 

 

Class.aiMatch.aimatchEditSettingsController.getApiUrlValue: line 10, column 1 Class.aiMatch.testaimatchOpportunityGrab.testEditSettingsControllerNeg: line 147, column 1

 

1 error of:

 

System.DmlException: Update failed. First exception on row 0 with id 006U0000007zk5DIAQ; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, aiMatch.aimatchOpportunityGrabTrigger: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.aiMatch.aimatchOpportunityGrabTrigger: line 22, column 1: []

 

Stack trace of above error:

Class.aiMatch.testaimatchOpportunityGrab.aimatchOpportunityGrabTest: line 25, column 1

 

 

 

The app works as expected. I've just gotten back into working with Apex after a year or so. Been working on Ruby and Javascript projects all year so I quite a bit rusty... :(

 

Any help is much appreciated!

 

 Here is my test class:

 

public class testaimatchOpportunityGrab {

    private static testmethod void aimatchOpportunityGrabTest() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');


        System.runAs(u) {
            
            List<Opportunity> listOpportunity = new List<Opportunity>();
                    
            // Create Opportunity test data
            Opportunity o = new Opportunity (name = 'test', campaign_created_in_aimatch__c = true, ownerid = '005U0000000gvRnIAI',
                                                        stagename = 'Renew', closedate = system.today(), aimatch_advertiser__c = 'a00U00000016hLW',
                                                        campaign_start_date__c = Date.today(), campaign_end_date__c = Date.today() + 30);
            insert o;                                                                                                  
            
            test.startTest();
            listOpportunity.add(o);
            
            update listOpportunity;


            test.stopTest();    
        
        }

    }    
    
    private static testMethod void testXmlApiCall() {
        //First, build the http request
        aimatchXmlApiCall testWebCallout = new aimatchXmlApiCall();
        String campName = 'Testcamp';
        String ownerName = 'testMe';
        String ownerEmail = 'test@email.com';
        String advertiserID = '12';
        String sDate = '2011-02-08';
        String eDate = '2011-02-09';
        
        HttpRequest req = testWebCallout.buildWebServiceRequest(campName, ownerName, ownerEmail, advertiserID, sDate, eDate);
   
        //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.  
        //Now, since we can't execute the actual web service, 
        //write apex code to build a sample HttpResponse object
      
        String xmlRes = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser></advertisers>';
      
        HttpResponse res = new HttpResponse();
        res.setBody(xmlRes);
        
        //Apply test data and attributes to the HttpResponse object as needed
        testWebCallout.handleWebServiceResponse(res, ownerEmail);
  
    }

    private static testMethod void testGetAdvertisersXmlApiCall() {
      //First, build the http request
        aimatchGetAdvertisersXmlApiCall testWebCallout  = new aimatchGetAdvertisersXmlApiCall();
        HttpRequest req = testWebCallout.buildWebServiceRequest();
   
      //NOTE - WE DO NOT EXECUTE THE METHOD, invokeWebService.       
      //Now, since we can't execute the actual web service, 
      //write apex code to build a sample HttpResponse object
      
      String xmlRes = '<advertisers type="array"><advertiser><id type="integer">7</id><name>ABC Telecom</name></advertiser></advertisers>';
      
      HttpResponse res = new HttpResponse();
      res.setBody(xmlRes);
      
      //Apply test data and attributes to the HttpResponse object as needed
      testWebCallout.handleWebServiceResponse(res);
  
    }

    private static testmethod void testEditSettingsControllerPos() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');
            
            list<aimatch_conf__c> theConf = [select id, name from aimatch_conf__c where name = 'settings' limit 1];
            list<aimatch_conf__c> updateConf = new list<aimatch_conf__c>();
            
            for(aimatch_conf__c con : theConf) {

                aimatch_conf__c thisConfVal = new aimatch_conf__c(Id=con.id);
                
                thisConfVal.name = 'settings';
                thisConfVal.aimatch_api_url__c = 'http://url.com';
                thisConfVal.aimatch_api_key__c = '123424351';
                thisConfVal.aimatch_schedule__c = '0 56 10 * * ?';
                thisConfVal.campaign_start_date_field_name__c = 'campaign_Start_Date__c';
                thisConfVal.campaign_end_date_field_name__c = 'campaign_End_Date__c';
                updateConf.add(thisConfVal);
            }
            upsert updateConf;

        System.runAs(u) {
                        
            aimatchEditSettingsController.getApiUrlValue();
            aimatchEditSettingsController.getApiKeyValue();
            aimatchEditSettingsController.getAdvSchValue();
            aimatchEditSettingsController.getCampStartDateFieldNameValue();
            aimatchEditSettingsController.getCampEndDateFieldNameValue();
            
            aimatchEditSettingsController editSettingsController = new aimatchEditSettingsController();
            editSettingsController.schAdv();
            editSettingsController.save();
        
        }
            
    }

    private static testmethod void testEditSettingsControllerNeg() {
        
        Profile p = [select id from profile where name='System Administrator']; 
        User u = new User(alias = 'standt', email='sysadmin@testorg.com', 
            emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, 
            timezonesidkey='America/Los_Angeles', username='aimatchtest@testorg.com');
            
            list<aimatch_conf__c> theConf = [select id, name from aimatch_conf__c where name = 'settings' limit 1];
            list<aimatch_conf__c> updateConf = new list<aimatch_conf__c>();
            
            for(aimatch_conf__c con : theConf) {

                aimatch_conf__c thisConfVal = new aimatch_conf__c(Id=con.id);
                
                thisConfVal.name = 'settings';
                thisConfVal.aimatch_api_url__c = '';
                thisConfVal.aimatch_api_key__c = '';
                thisConfVal.aimatch_schedule__c = '';
                thisConfVal.campaign_start_date_field_name__c = '';
                thisConfVal.campaign_end_date_field_name__c = '';
                updateConf.add(thisConfVal);
            }
            upsert updateConf;

        System.runAs(u) {
            
            aimatchEditSettingsController.getApiUrlValue();
            aimatchEditSettingsController.getApiKeyValue();
            aimatchEditSettingsController.getAdvSchValue();
            aimatchEditSettingsController.getCampStartDateFieldNameValue();
            aimatchEditSettingsController.getCampEndDateFieldNameValue();
            
            aimatchEditSettingsController editSettingsController = new aimatchEditSettingsController();
            editSettingsController.schAdv();
            editSettingsController.save();
        
        }
    }
     
}

 

 

 

  • August 08, 2012
  • Like
  • 0

Hi Pals,

 

Is it possible to parse/process file uploaded( for e.g. a .csv file) in apex and and fetch records? From what I know, when a file is uploaded from suppose a VF page, we will receive a Blob of that file. But there is no mechanism as such to parse that Blob and see what data is exactly is inside it. I know this I/O processing can be easily done in .Net/Java. But usually a .Net/Java solutions is not what a customer expects because of the extra hosting/costing/whatever the other reasons. So, I want to know if this possible in Apex at all ? I searched boards and also IdeaExchange but did not find any confident answer. Any help is very much appreciated.

 

Thanks

Vishnu

I need help with a design issue and what happens in Batch Apex.

 

Setup

This is the scenario we have: We have a territory object, then when you update a single field needs to update a field on UPTO hundreds of thoursands of contacts. To do this, I am using Batch Apex. And invoking it on the territory record before it’s updated.

 

 

Question:

  1. Say the user updates the territory from A to B, and clicks save. This causes a big batch of contacts to get updated and take a while Then, he changes B to C. Are we guaranteed that the final update on all impacted records will be C? How come?

  2. Or, is there a way to schedule your batch jobs? I’m looking into asyncApexJob and using that as a framework…

  3. Is there a better design?

Hello,

 

I have some code that iterates through a list of Project_Role__c records and if the role__c field is null, remove it from the list.

 

Here is the code I have so far:

 

for(Integer j = 0; j < roles.size(); j++){
   if(roles.get(j).role__c == null){
        roles.remove(j);
   }
}

 For some reason the logic isn't working. 

 

*Note: Role__c is a picklist, should I be checking to see if Role__c == '' instead?

trigger volumes on case (before Insert, before Update) {
        for(case x : Trigger.New){        
                     

       if (x.region__c == 'South West'){   
           x.consignments_volumes__c = Volumes__c.getinstance('1. January 2012 SW').Id__c; 

       if (x.region__c == 'North West'){   
           x.consignments_volumes__c = Volumes__c.getinstance('2. February 2012').Id__c;
                            
} 
   }}}

Hi, relatively new to this so I appreciate any help!

 

Can anyone advise why this trigger does not work? it's referencing a custom setting.

 

If I remove the 'if' line, then it seems to work. Any ideas?

 

Thank you

 

 

Hi,

 

i am new to salesforce.

 

i have an doubt how to add values to the nested list

 i have declared a nested list(as below) then i need to add values to that nested

List<List<Integer>> my_list_2 = new List<List<Integer>>();

Regards,

Bharath

I want to use a managed package controller in my custom visualforce page. But iam getting the error as managed package class is not visible.

IS there any way we can do that?

 

Thanks

 

HI , 

I need help with a trigger

 

the trigger should only allow an account to be enabled as partner account if the account record type is 'Business account'

 

Thanks

Hi

I have created an apex class to verify if there is a new account isn't on the lead and if it's the case, I retrieve the value of the lead to update my account.

But when I try an exemple, I have an error : System.FinalException: Record is read-only

 

My apex class is :

//mise à jour de compte si doublons

global class VerifNoLead implements  Database.Batchable<sObject> {

global final String query;
global final Account compte;

global VerifNoLead (String q, Account ld)
{
   query = q;
   compte= ld;
}

global Database.QueryLocator start(Database.BatchableContext BC){

   return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<sObject> scope){
        for(sObject s : scope){
            Lead leadO = (Lead)s; 
            //champs identification du compte (non modifiable)
            if(leadO.Salutation != null){compte.Salutation = leadO.Salutation;}
            System.debug(compte.Salutation);
            if(leadO.FirstName != null){compte.FirstName = leadO.FirstName;}
            if(leadO.LastName != null){compte.LastName = leadO.LastName;}
            
            compte.PersonLeadSource = leadO.LeadSource;            
         
            //information sur l'adresse. Si un est modifié, tous le sont
            if(compte.PersonMailingStreet ==null && compte.PersonMailingCity ==null && compte.PersonMailingPostalCode ==null && compte.PersonMailingCountry ==null && compte.PersonMailingState ==null)
            {
                compte.PersonMailingStreet = leadO.Street;
                compte.PersonMailingCity = leadO.City ;
                compte.PersonMailingPostalCode = leadO.PostalCode;
                compte.PersonMailingCountry = leadO.Country;
                compte.PersonMailingState = leadO.State ;
            }

            if(compte.PersonHomePhone ==null){compte.PersonHomePhone = leadO.Phone ;}
            if(compte.PersonMobilePhone ==null){compte.PersonMobilePhone =  leadO.Telephone_portable__c ;}          
            if(compte.Rating ==null){compte.Rating = leadO.Rating ;}
            if(compte.Type_d_utilisation__c ==null){compte.Type_d_utilisation__c = leadO.Type_d_utilisation__c ;}        
          
            //champ relatif à la newsletter
             if(compte.Inscription_la_newsletter__c == false && compte.D_sinscription_la_newsletter__c == false){
                if(leadO.Inscription_la_newsletter__c == true){
                    compte.Inscription_la_newsletter__c = true;
                    compte.Date_d_inscription_la_newsletter__c = leadO.Date_d_inscription_la_newsletter__c;
                    compte.D_sinscription_la_newsletter__c = leadO.D_sinscription_la_newsletter__c;
                    compte.Date_de_d_sinscription_la_newsletter__c = leadO.Date_de_d_sinscription_la_newsletter__c;
                }
            }
            

//System.debug(compte.Id);
            if(compte.Id != null){update compte;System.debug('mise à jour ok');
            }
            else {System.debug ('erreur compte');}
            if(leadO.Id != null){delete leadO;
            System.debug('leadO.id !=null');}
            else{System.debug('erreur leadO');}
            }
}



global void finish(Database.BatchableContext BC){

        System.debug('fini');
       
}

public static testmethod void testVerifNoLead (){
    List <Lead> ld = new List<Lead>();
    for(integer i = 0; i<2; i++){
        Lead l = new Lead(Adresse_mail__c='test'+i+'@mail.com',LastName='test', Inscription_la_newsletter__c =true);
        ld.add(l);
    }
    insert ld;


   
     Test.startTest() ;

     Account lnew = new Account(
            Salutation = 'M.',
            FirstName ='Hélène',
            LastName = 'test',
            Adresse_mail__c = 'test1@mail.com',
            PersonLeadSource = 'Newsletter',
           // Origine_connaissance_Kiwatch__c ='',
            Numero_client__c = 0,
            /*accepte_jeux__c = true,
            Date_inscription_au_jeu__c = ,
            Email_parr__c = 'h.broussin@kiwatch.com',
            Email_parrainage_2__c = '',
            Email_parrainage_3__c = '',
            Email_parrainage_4__c = '',
            Email_parrainage_5__c = '',*/
         //   PersonMailingStreet = '',//'39, rue des étoiles',
           // PersonMailingCity = '',//'laval',
         //   PersonMailingState = '',//'pays de loire',
          //  PersonMailingPostalCode = '',//'53000',
          //  PersonMailingCountry = '',//'france',
            PersonHomePhone = '0900000000',
            PersonMobilePhone = '070809101112',
            Rating = 'Froid',
           // Date_d_inscription_la_newsletter__c = '29/05/2012',
           // Date_de_d_sinscription_la_newsletter__c = '',
            Inscription_la_newsletter__c = false,
            D_sinscription_la_newsletter__c = false,
            Raison_de_la_d_sinscription__c = '',
            /*locataire__c = true,
            proprietaire__c = false,
            alarme__c = false,
            videosurveillance__c = false,
            alarme_et_videosurveillance__c = false,
            pas_de_systeme__c = true,*/
            Type_d_utilisation__c = 'Pro',
            demande__c = '',
            Demande_contact__c = '',
            Objet_demande__c = '',
            //Date_d_abonnement__c,
            //Date_fin_de_contrat__c,
            Raison_fin_de_contrat__c ='',
            //Date_de_l_abonnement_actuel__c,
            Abonnement__c='Pro');
              
        String query = 'SELECT  Salutation, FirstName , Adresse_mail__c, LastName, Num_ro_piste__c, LeadSource, Origine_connaissance_Kiwatch__c, Client__c, D_sinscription_la_newsletter__c, Inscription_la_newsletter__c, Raison_de_la_d_sinscription__c, Date_de_d_sinscription_la_newsletter__c, Date_d_inscription_la_newsletter__c, Street, City, State, Country, PostalCode, Phone, Telephone_portable__c    FROM Lead WHERE Adresse_mail__c=\'' + lnew.Adresse_mail__c + '\'  LIMIT 2';

       VerifNoLead batchApex = new VerifNoLead(query, lnew );
       ID batchprocessid = Database.executeBatch(batchApex);
   
       Test.StopTest();
 }
      
       
}

 and my trigger :

trigger RechercheDoubleCompte on Account(after insert) {
    for (Account a : Trigger.new) {   
                   
     String query = 'SELECT Salutation, FirstName , Adresse_mail__c, LastName, Numero_client__c, PersonLeadSource, D_sinscription_la_newsletter__c, Inscription_la_newsletter__c, Raison_de_la_d_sinscription__c, Date_de_d_sinscription_la_newsletter__c, Date_d_inscription_la_newsletter__c   FROM Account WHERE Adresse_mail__c=\'' + a.Adresse_mail__c + '\' AND   Id!=\'' + a.Id + '\' LIMIT 100';
     String query2 = 'SELECT  Salutation, FirstName , Adresse_mail__c, LastName, Num_ro_piste__c, LeadSource,Phone, Telephone_portable__c, Rating,Type_d_utilisation__c , Origine_connaissance_Kiwatch__c, Client__c, D_sinscription_la_newsletter__c, Inscription_la_newsletter__c, Raison_de_la_d_sinscription__c, Date_de_d_sinscription_la_newsletter__c, Date_d_inscription_la_newsletter__c, Street, City, State, Country, PostalCode  FROM Lead WHERE Adresse_mail__c=\'' + a.Adresse_mail__c + '\'  LIMIT 100';
      

       UpdateFieldAccount batchApex = new UpdateFieldAccount(query, a );
       ID batchprocessid = Database.executeBatch(batchApex);
       
       VerifNoLead batchApex2 = new VerifNoLead(query2, a );
       ID batchprocessid2 = Database.executeBatch(batchApex2);
    
    }
            
}

 

 

  • June 04, 2012
  • Like
  • 0

I've had this problem now for months and finally am resorting to custom coding.

 

All I need to be able to do is figure out how many days it has been since a lead or account has been contacted.

We have a caveat though in that we need to filter out marketing activities so there's a filter that looks like "Assigned != 'Marketing'" at the Tasks/Events level.

 

How difficult would it be to write a trigger in Apex to fill in the most recent Completed Task/Event not assigned to "Marketing" date on an account or lead record?

Is this even possible? And would it be on or before an update/insert? 

 

I'm extremely new to apex coding, but am hoping someone else has had a similar problem and may even have a bit of code to share.

 

Thank you.

I have tried to bulkify this trigger many times, but have failed as when I mass update my opportunities, most of my opportunity probability fields have been updated with the wrong values. How do I solve this problem and bulkify the trigger?

 

Trigger:

 

trigger ForecastOverride on Opportunity (Before Update) {

    Set<Id> bIds = new Set<Id>();
    user u;
    for(Opportunity op : trigger.new){
    System.debug('**** 0 op id : '+op.ForecastCategoryName);
    bids.add(op.id);
   }     
    
    if(StaticClass.doNotExecute ==true)
{
    system.debug('Inserting'+StaticClass.doNotExecute);
    for(Opportunity o:trigger.new)
    {
     bIds.add(o.id);
    Decimal m = 10;
    Decimal l = 0;
    Decimal t = 25;
    Decimal bc = 75;
    Decimal c = 90;
    Decimal p = 50;
    Decimal w = 100;
    
    if(trigger.new[0].Opp_Owner__c != trigger.new[0].Current_User__c){

    if (trigger.new[0].Forecast_Category_Override__c != trigger.old[0].Forecast_Category_Override__c)
     {
         o.ForecastCategoryName = o.Forecast_Category_Override__c;
        
        if (trigger.new[0].Forecast_Category_Override__c == 'Best Case') {
        o.Probability = bc;
        }
        if (trigger.new[0].Forecast_Category_Override__c == 'Commit') {
        o.Probability = c;
        }
        if (trigger.new[0].Forecast_Category_Override__c == 'Omitted') {
        o.Probability = m;
        }
        if (trigger.new[0].Forecast_Category_Override__c == 'Pipeline') {
        o.Probability = p;
        }  
          }   
   
    if (trigger.new[0].StageName == 'Closed Won')
     {
        o.probability = w;
        o.ForecastCategoryName = 'Closed';
        o.Forecast_Category_Override__c = 'Closed';
        
        }   
    if (trigger.new[0].StageName == 'Prospecting')
     {
        o.probability = m;
        o.ForecastCategoryName = 'Omitted';
        o.Forecast_Category_Override__c = 'Omitted';
        
        }
    if (trigger.new[0].StageName == 'Qualifying')
     {
        o.probability = m;
        o.ForecastCategoryName = 'Omitted';
        o.Forecast_Category_Override__c = 'Omitted';

       } 
    if (trigger.new[0].StageName == 'Proposal')
     {
        o.probability = t;
        o.ForecastCategoryName = 'Pipeline';
        o.Forecast_Category_Override__c = 'Pipeline';

       } 
    if (trigger.new[0].StageName == 'Proposal Delivered' && trigger.new[0].ForecastCategoryname == 'Pipeline')
     {
        o.probability = p;
        o.ForecastCategoryName = 'Pipeline';
        o.Forecast_Category_Override__c = 'Pipeline';

       } 
    if (trigger.new[0].StageName == 'Proposal Delivered' && trigger.new[0].ForecastCategoryname == 'Best Case')
     {
        o.probability = bc;
        o.ForecastCategoryName = 'Best Case';
        o.Forecast_Category_Override__c = 'Best Case';

       }
    if (trigger.new[0].StageName == 'Proposal Delivered' && trigger.new[0].ForecastCategoryname == 'Omitted')
     {
        o.probability = m;
        o.ForecastCategoryName = 'Omitted';
        o.Forecast_Category_Override__c = 'Omitted';

       }        
   if (trigger.new[0].StageName == 'Negotiation' && trigger.new[0].ForecastCategoryname == 'Best Case')
     {
        o.probability = bc;
        o.ForecastCategoryName = 'Best Case';
        o.Forecast_Category_Override__c = 'Best Case';

       }  
  if (trigger.new[0].StageName == 'Negotiation' && trigger.new[0].ForecastCategoryname == 'Commit')
     {
        o.probability = c;
        o.ForecastCategoryName = 'Commit';
        o.Forecast_Category_Override__c = 'Commit';

       }  
  if (trigger.new[0].StageName == 'Negotiation' && trigger.new[0].ForecastCategoryname == 'Omitted')
     {
        o.probability = m;
        o.ForecastCategoryName = 'Omitted';
        o.Forecast_Category_Override__c = 'Omitted';

       }   
   if (trigger.new[0].StageName == 'Closed Lost')
     {
        o.probability = l;
        o.ForecastCategoryName = 'Omitted';
        o.Forecast_Category_Override__c = 'Omitted';

       }
   }
  }

}
}

I am attempting to populate my lookup field from Accounts using a query to get the correct id.  I need to update several thousand records, but my existing trigger will not do more than 100.  Here is the code.  What changes do I need to make for this to work?

trigger CustNameStatus on Sales_History__c (before insert, before update){          

 List<Sales_History__c> HWA = [select id, Customer__c, JDE_Cust__c, Cust_Name__c

                                                     from Sales_History__c where Id IN :Trigger.newMap.keySet()];        

 

for(Sales_History__c h: HWA){     

string JDE = h.JDE_Cust__c;     

 system.debug('JDE CUST = ' + h.JDE_Cust__c);        

 Account a = [Select Id,Name,JDE_Customer__c from Account where JDE_Customer__c =: JDE limit 1 ] ;

                 h.Customer__c = a.id;      

                 h.JDE_Cust__c = a.JDE_Customer__c;       

                 h.Cust_Name__c = a.Name;

                     system.debug('Account = ' + a);       

                      system.debug('Sales History = ' + h); 

                    }

            }

  • June 01, 2012
  • Like
  • 0

Here's my sample code.

 

AddFields, if located in constructor, works; if not, will cause exception:

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: 

 

<apex:page standardController="account" extensions="LearnVFaddFields" recordSetVar="accounts">
   <apex:form >
   <apex:commandButton value="Change" action="{!changeFields}"/>
   <apex:pageblock >
       <apex:pageblockTable value="{!accounts}" var="acct">
           <apex:repeat value="{!fields}" var="f">
               <apex:column value="{!acct[f]}"/>
           </apex:repeat>
       </apex:pageblockTable>
   </apex:pageblock>
   </apex:form>
</apex:page>



public with sharing class LearnVFaddFields {
    ApexPages.StandardSetController controller;

    public List <String> fields {
        get;
        private set;
    }

    public LearnVFaddFields(ApexPages.StandardSetController controller) {
        List <String> fields = new List <String>{'Name', 'Rating'};
        this.controller = controller;
        updateRows(fields);
    }
    
    private void updateRows(List <String> fields) {
        this.fields = fields;
        controller.reset(); 
        controller.AddFields(fields);        
    }
    
    public PageReference changeFields() {
        List <String> fields = new List <String>{'Phone', 'type'};
        updateRows(fields);
        return null;
    }
}

 


I have saved data before but not from a datatable, basically what i want to do is save each row of data as a new record in my object. Not sure how to do this. It displays the data exactly how i want it just need to save it. I really need some direction any help would be appreciated.

 

<apex:page standardController="Zones_List__c" extensions="RAPI"  showHeader="false" sidebar="false" standardStylesheets="false">
  Zones
  
  
  <apex:outputPanel id="databox" >                   
    <apex:outputPanel id="dataPanel">     
       <apex:outputText value="{!DisplayZones}"  escape="false"/>
    </apex:outputPanel>
  </apex:outputPanel>
  
   <apex:form >
         
         <apex:commandButton id="ZoneUpdate" action="{!ZUpdateList}"  value="Update Zones" />
         <apex:inputText id="account_num" value="{!Zones_List__c.Account__c}"/>         
        <apex:pageBlock title="Zones" id="tblId">
          <apex:dataTable value="{!ZS}" var="r" cellPadding="4" border="1">
           <apex:column >
            <apex:facet name="header">Zone</apex:facet>
            <apex:outputText value="{!r}" />
            <!--<apex:inputText id="rZone" value="{!Zones_List__c.Rapid_Zone_Name__c}"/> -->
           </apex:column>
           <apex:column >
             <apex:facet name="header">Equipment</apex:facet>
              <apex:selectList size="1" id="equip" value="{!Zones_List__c.Equipment_Points__c}">
                <apex:selectOptions value="{!Equip}"/>
              </apex:selectList>            
           </apex:column>
           
           <apex:column >
             <apex:facet name="header">Location</apex:facet>
              <apex:selectList size="1" id="location" value="{!Zones_List__c.Location__c}">
                <apex:selectOptions value="{!ZLoc}"/>
              </apex:selectList>
            
           </apex:column>
           
          </apex:dataTable>          
         </apex:pageBlock>
         
     </apex:form>

</apex:page>

 

I have a super simple page and a button with a rerender property.  All it should be doing is rerendering 2 different panels.  For some reason this rerender never happens, but I had put debugs in ensuring that my method does get called.  Any ideas?

 

Page

<apex:page controller="CohortTest2" sidebar="false">
	<apex:form >
		<apex:outputPanel id="pnl1" rendered="{!showMe}">
			<apex:outputText value="dum dum dum" />
		</apex:outputPanel>
		<apex:outputPanel id="pnl2" rendered="{!!showMe}">
			<apex:outputText value="blah blah blah" />
		</apex:outputPanel>
		<apex:commandButton value="button" action="{!test}" rerender="pnl1, pnl2" />
	</apex:form>
</apex:page>

 Controller:

public with sharing class CohortTest2
{
	public boolean showMe{get;set;}
	public CohortTest2()
	{
		showMe = false;
	}
	
	public void test()
	{
		showMe = !showMe;
		//return new PageReference('/apex/Cohort_SetupWizard2');
		//return null;
	}
}

 

 

 

I have a customer portal that I need some text to display in whatever language the User is using.  A couple of languages we need to support are not supported by Salesforce at all.  

Bengali

Haitian Creole

 

Is this doable?  If so.... where do I begin?

I have a customer portal that I need some text to display in whatever language the User is using.  A couple of languages we need to support are not supported by Salesforce at all.  

Bengali

Haitian Creole

 

Is this doable?  If so... where do I begin?

Currently, we have a project that has 45 tabs.  My teams now want us to begin working in our own development orgs, and then deploying changes to SVN.  I can't seem to find Salesforce support to request an increase to the tab limit.  Can anyone share this info with me?

I read some older posts saying that Chatter is not enabled in the Customer Portal.  Can anyone confirm if this is still true or not?

I was wondering if there is a special process to go through in order to post a blog on developerforce.  Are the blogs there posted elsewhere and then eventually Salesforce posts them after a special process or are those users allowed to post blogs directly to Salesforce?

I need to insert Content into my test class so that I can test a method.  The problem is that I have custom fields and get the error:

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, You cannot set custom fields or tags on a document published into a personal library. Fields set: Type of Document,Quarter: []

 

So I need to figure out how to publish into a personal library to set these fields.  Does anyone know how to do this through code?

 

 

ContentVersion version = new ContentVersion();
version.Title = 'test';
version.ContentUrl = 'www.google.com/';
version.Quarter__c = 'Test Quarter';
version.Type_of_Document__c = 'Test type';
insert version;

I also tried creating an account in the test class and setting the

version.FirstPublishLocationId = acc.Id;

and got the error:

 

System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, Content cannot be inserted as a child of record 001V0000007AcyK.: [FirstPublishLocationId] 

 

 

On the Content Version object there is a TagCsv field.  I wrote a trigger to set this field to the quarter/type of document but it doesn't seem to work.  Anyone have any ideas?

 

trigger ContentVersionTriggers on ContentVersion (before insert, before update)
{
	if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate))
		TagContentTH.tagContent(Trigger.new);
}

 

public with sharing class TagContentTH
{
	public static void tagContent(List<ContentVersion> triggerNew)
	{
		for (ContentVersion currContent: triggerNew)
		{
			System.debug('did it make it here?');
			System.debug('doc type = ' + currContent.Type_Of_Document__c);
			System.debug('content type = ' + currContent.Quarter__c);
			currContent.TagCsv = currContent.Type_Of_Document__c + ', ' + currContent.Quarter__c;
			System.debug('tagcsv = ' + currContent.TagCsv);
		}
	}
}

 Output:

did it make it here?

doc type = somethinghere

content type = Q6

tagcsv = somethinghere, Q6

 

Wasn't sure what board to ask this question on... but is there somewhere that we can go that tells how many people have passed each of the certification exams?  I just passed the Advanced Developer and I'm curious as to the number.

Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id: []

 

This happens when I use code to create an object, then a workflow changes the owner for a normal user, and then I create another object that uses this Id.

 

Does anyone have a way to get around this without removing the 'with sharing' from my class?

Is there a way to add CSS to std pages?

Inside of a custom button, I have the javascript&colon;

 

location.replace('/email/author/emailauthor.jsp?retURL=%2F{!Case.Id}&p24={!Case.SuppliedEmail}&rtype=003&p3_lkid={!Case.Id}&new_template=1&template_id=00XS0000000Qfeb&save=1');

 

When it navigates to the new page, everything fills out correct, but it doesn't send the email and redirect me right away.  Instead I get the error:

 

The page you submitted was invalid for your session. Please click Save again to confirm your change.

 

 

Does anyone know how I might be able to correct this?

When I create a new User, is there a way I can have a default Chatter message when they go to their Chatter page?

  • September 13, 2011
  • Like
  • 0

Is there a way that when a new user is created, I can post a default Chatter message for them to view when they go to their Chatter page?

  • September 13, 2011
  • Like
  • 0

I wanted to use the Schema.getGlobalDescribe() in order to loop through all of the fields in Accounts and make an update to them.

 

Basically one of our clients have clients that need to upload data to their Salesforce.  Currently they upload this using the data loader (or something, i'm not quite sure but it doesn't matter) into a custom object, and then a batch gets run at night that converts this to Account.  This custom object matches Account on their system, which is slightly different from our clients.  

 

Basically I want to have the batch code to convert the custom object to an account, but whenever they add new fields to the custom object/account in the database we don't need to update the code.  The fields in the custom object and Account are generally similar, but there are a few special cases in which we can take care of manually.  Does anyone know how I might be able to access all of these fields, and then update them through a loop?  I have been looking into this, and it seems the only things I have found is getting the describe of the fields but not how to use this to access the field on the object.

 

Hopefully this makes sense and I would be glad to clarify anything.

Our client has a problem, where basically they have over 1600 unused reports and want a good way to move all of these old reports into an unused reports folder.  You cannot do this through apex code or the data loader.  I have also tried this using the Partner API and got an error basically saying that you cannot make changes to the reports.

 

Does anyone know of a way to basically change what folder a report is in through a Webservice API?

Right now I'm just trying to establish a connection between my java app and Salesforce, but it isn't working out very well.  For some reason on my connection = new PartnerConnection(config); line I always error.

 

[ApiFault  exceptionCode='INVALID_LOGIN' exceptionMessage='Invalid username, password, security token; or user locked out.'

 

I have already confirmed that my username/password/security token are all correct.

 

public static void main(String[] args)  {   

ConnectorConfig config = new ConnectorConfig();   

config.setUsername("MYLOGIN");   

config.setPassword("MYPW&MYTOKEN");       

PartnerConnection connection;

try    {        

connection = Connector.newConnection(config);  

 } catch (ConnectionException e)    {     

// TODO Auto-generated catch block      e.printStackTrace();    }   }

Does anyone know how to change the Reports OwnerId through code?  I get the error, Field is not writeable: Report.OwnerId.

 

Basically the reason for this is that i'm doing a query to return Reports and if they are returned I want to place them in a specific folder.

 

List<Report> temp = [SELECT name, LastRunDate FROM Report WHERE LastRunDate >=: (System.today() - 90)];

for (Report curr: temp)     

    curr.OwnerId = myfolder.id;

upsert temp;

currently I have

DateTime.now().format('MM/dd/yyyy hh:mm a', 'EST');

 

but I would like to have 

DateTime.now().format('MM/dd/yyyy hh:mm a', 'ET');

 

The issue is that when I put ET as the timezone it defaults the timezone to GMT since ET is not a correct time zone.  How do I accomplish this?

I have a page that has a button that calls window.close(); in javascript.  For some reason the window.close(); never gets executed and i cannot figure out why.  I have tried in ie, firefox and chrome browsers and none will work.

 

 

<apex:page controller="CustAcctAlertDetailController" sidebar="false" showHeader="false" standardStylesheets="false">
  <style>
    body{background-color: LightGrey;}
  </style>
  <apex:form >
  <div>
    <apex:outputPanel >
      <span style="font-size:20px;font-weight:bolder;">Alert Details</span>
      <span style="font-size:12px">
      <table>
        <tr>
          <td width="90px"><apex:outputText value="{!details.detailAccountID}" /></td>
          <td><apex:outputText value="{!details.subAcctName}" /></td>
        </tr>
        <tr>
          <td><apex:outputText value="{!details.msgCategory}" /></td>
          <td>address line 2</td>
        </tr>
        <tr>
          <td /><td>address line 3</td>
        </tr>
      </table><br/>
      <span style="font-size:19px;font-weight:bolder;">Subject: {!details.msgSubject}</span>
      <table>
        <tr>
          <td width="75px">Date:</td>
          <td>{!details.msgCreateDate}</td>
        </tr>
        <tr>
          <td>Alert Type:</td>
          <td width="250px">{!details.msgAlertType}</td>
          <td width="90px">Master Account:</td>
          <td>{!details.masterDetailAccountID}</td>
        </tr>
        <tr>
          <td>Priority:</td>
          <td>{!details.msgPriority}</td>
          <td>Status:</td>
          <td>{!details.status}</td>
        </tr>
        <tr>
          <td>Alert ID:</td>
          <td>{!details.alertID}</td>
          <td>Action:</td>
          <td>Not Required</td>
        </tr>
        <tr>
          <td>Task ID:</td>
          <td>N/A</td>
        </tr>
      </table><br/>
      <span style="font-size:19px;font-weight:bolder;">From: {!details.msgFromName}</span><br/>
      <span style="font-size:19px;font-weight:bolder;">Comment:</span><br/> {!details.msgText}
      <br/><br/>
      If you have any questions, please Contact your Service Team.<br/><br/>
      </span>
      <table>
        <tr>
          <td style="border:2px dashed orange;background-color: White;font-size:12px;">
            Action is required on check and journal requests by 12:00 noon ET on the requested pay date to ensure payment. Moneylink requests
            require action one business day before the requested pay date.<br/>
            You may update the transaction online, place trades online, as needed, or for assistance resolving this issue please contact your service
            or trading team.<br/>
            <apex:outputLink value="" style="color:blue;">Go to Schwab Advisor Center</apex:outputLink>
          </td>
        </tr>
      </table>
    </apex:outputPanel>
    <table width="100%">
      <tr>
        <td><apex:commandButton value="Archive" style="width: 100px;" /></td>
        <td style="text-align: right;">
          <apex:commandButton value="Close" style="width: 100px;" onClick="window.close();" />
          <input value="Close" type="button" style="width: 100px;" onClick="window.close();" /></td>
      </tr>
    </table>
    <apex:actionSupport />
  </div>
  </apex:form>
  <script type="text/javascript">
    function myclose()
    {
      window.close();
      return false;
    }
  </script>
</apex:page>

 

On the Content Version object there is a TagCsv field.  I wrote a trigger to set this field to the quarter/type of document but it doesn't seem to work.  Anyone have any ideas?

 

trigger ContentVersionTriggers on ContentVersion (before insert, before update)
{
	if (Trigger.isBefore && (Trigger.isInsert || Trigger.isUpdate))
		TagContentTH.tagContent(Trigger.new);
}

 

public with sharing class TagContentTH
{
	public static void tagContent(List<ContentVersion> triggerNew)
	{
		for (ContentVersion currContent: triggerNew)
		{
			System.debug('did it make it here?');
			System.debug('doc type = ' + currContent.Type_Of_Document__c);
			System.debug('content type = ' + currContent.Quarter__c);
			currContent.TagCsv = currContent.Type_Of_Document__c + ', ' + currContent.Quarter__c;
			System.debug('tagcsv = ' + currContent.TagCsv);
		}
	}
}

 Output:

did it make it here?

doc type = somethinghere

content type = Q6

tagcsv = somethinghere, Q6

 

Hi,

 

I am writing a trigger to show a document in a custom field when the status of the related document is  completed in the DocuSign Status object.

how to fetch the document's link in the custom field?

I have built a custom report using Visual Force. I am trying to give the end user the ability to sort the report by a few different fields. I have created a pick list on a Custom Object that contains the field names (API Names) that the user can sort by. In my class I query the Custom object to get the field the end user wants to sort by, I store that in a variable. I then want to use that vairble to order by my SOQL statement that builds the report.

 

Here is my Query to build the report:

 

String shipping = '%Small Parcel%';
String Stage = 'Closed Won';

String Query = 'SELECT Estimated_Ship_Date__c, Date_Shipped__c, Opportunity.CloseDate, Opportunity.Account.Name, From OpportunityLineItem WHERE Opportunity.StageName = :Stage and (NOT ShippingType__c like :shipping) ORDER BY ';
Query += SortBy ;

List<OpportunityLineItem> myOCR = Database.query(Query);

return myOCR;

 

When I hard code the SortBy Variable the query works perfectly however I need to set the SortBy varible to the result of another query and I cannot get the correct syntax. Here is what I have tried so far and none of these worked:

 

String SortBy = 'Select SortBy__C from Custom__c Where Name = FreightDashboard' ;

 

String SortBy = '(Select SortBy__C from Custom__c Where Name = FreightDashboard)' ;

 

String sortx = 'Select SortBy__C from Custom__c Where Name = FreightDashboard' ;
List<Custom__c> Sortby = Database.query(sortx);
Return Sortby;

 

list<Custom__c> Sortby;
list <Custom__c> customa = ([Select SortBy__C from Custom__c Where Name = 'FreightDashboard']);{
   for (Custom__c cx:customa){
   Sortby.add(cx.SortBy__C); //not sure on this syntax 
  }
}

 

 

list<Custom__c> Sortby;

  public list<Custom__c> getCustom__c() {

        Sortby = ([Select SortBy__C from Custom__c Where Name = 'FreightDashboard']);

        return Sortby;
}

 

 

As you can probably tell I am new to SOQL. I have experience with SQL but I am struggling with this Order by variable.

 

Thank you,

 

I am trying to make a custom page in my Customer Portal that shows ALL the cases of an account instead of just that specific user's. 

 

The SQL statement I am using in my VisualForce page to do this is:

 

    SELECT CaseNumber, AccountId, Subject FROM Case WHERE AccounttId = {!$User.AccountId}

 

However, I get this error:

 

    Error: Field AccountId does not exist. Check spelling 

 

How would I create this custom page that shows all cases?

  • September 25, 2012
  • Like
  • 0

I am a novice apex programmer and new to triggers. Please suggest me how can I write a trigger to fetch a value from Child__c object having a field named "No_of_child_count__c" and populate the same calue in Parent__c object having a field named "Count_parent__c".

We just need to update the parent field after insertion of new records in child object.

 

  • September 25, 2012
  • Like
  • 0
trigger CaseCloseTrigger on Case (after update){
        for(Case c : [SELECT id, Status FROM Case WHERE id in:trigger.new and Case.RecordTypeId = '0123000000001l1']){           
    if(c.Status == 'Completed' || c.Status == 'Closed'){                       
for(Training_Information__c customobj :
[Select Id, Status__c From Training_Information__c Where Case__c in: Trigger.newMap.keySet()]){
if(customobj.Status__c == 'Pending' || customobj.Status__c == 'Scheduled'){ trigger.new[0].addError('Training has not been Completed.');
}} } }}

 

I would like a way to queue up emails that I want to send on caught exceptions in various apex classes and triggers but I'm having a hard time figureing out how to queue them up and then know when to send them. I'd like something that in effect queues up emails and sends 5 seconds after the last email was added to the list. 

 

What is a good way of acheiving this? I've entertained several mehotds but all seem to have some kind of draw back.

 

I tried holding the emails in a list variable of a utility class but the class/variables have lost scope when the batch fires. 

 

I could insert a row into a table on each exception but I dont want to exceed SOQL/DML governer limits. 

 

It would be nice if there were some kind of class_beforeterminate event so I could send any emails before my utility class looses scope and is destroyed. 

 

Any ideas? Thanks. 

 

 

 

Hi, I wanted to Query as 

 

Consider there are more than  50000 records in lead in production.

 

[SELECT Count(id) from Lead Limit 1]

 

Idealy it Returns only one record.

as i understand as in docs its mentioned it will throw an Too many rows Exception. 

 

SO how can i avoid this Exception. Or Batch Apex is the only solution for this. 

  • September 13, 2012
  • Like
  • 0

I have a component that provides an autocomplete/type suggest list.

It's currently a component, but the object to search and the fields are hard-coded.

 

How can I get this to become a component where I can pass in the object name and the fields I want searched.

 

I have seen examples using Javascript Remoting, But that is causing me too many issues so far.

 

Can I achieve my goal without using Javascript Remoting?

 

Here is the Class:

global class AutoComplete {


public static String JSONString {get;set;}
public static sObject obj{get;set;}

public AutoComplete(){
	getDesignations();
}


global static String getDesignations(){
	List<Designation_Abbreviation__c> abbs = [Select Id,Name, Designation__r.Name from Designation_Abbreviation__c];
	List<String> designations = new List<String>();
	
	
	for(Designation_Abbreviation__c d: abbs){
		designations.add(d.Name +' - '+d.Designation__r.Name);
	}
	
	JSONString = JSON.serialize(designations);
	
	return JSONString;
}


}

 

Here is the component:

<apex:component controller="AutoComplete">
	<apex:includeScript value="{!URLFOR($Resource.AutoCompleteJQuery, 'AutoCompleteJQuery/jquery-1.8.1.min.js')}" />
	<apex:includeScript value="{!URLFOR($Resource.AutoCompleteJQuery, 'AutoCompleteJQuery/jquery-ui-1.8.23.custom.min.js')}" />
	<link rel="stylesheet" type="text/css"
		href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/themes/smoothness/jquery-ui.css" />


	<!-- Attributes Required for Component -->
	<apex:attribute name="objectname" description="The object to search and build autocomplete for." type="String" required="false" />
	<apex:attribute name="additionalfields" description="fields to search" type="String" required="false" />
	
	
	<script>

	$(function() {

		var availableTags = new Array();
		availableTags = {!JSONString};
		//alert(availableTags);
		
		$( "#tags" ).autocomplete({
			source: availableTags
		});
	});

</script>




<div class="demo">

<div class="ui-widget">
	<label for="tags">Tags: </label>
	<input id="tags" size="50"/>
</div>

</div> 
	
	
</apex:component>

 

Here is a page testing the component:

<apex:page >
    <apex:form >
       <c:AutoCompleteComponent />
    </apex:form>
</apex:page>

 

HI, this is my first trigger. Kindly tell me what mistake am doing?

 

1. The problem is : Every time this trigger is executed the record gets inserted twice...

 

How to stop this?

 

Please find the code below:

trigger SalesOrder on Sales_Order__c (after update){

    List <Sales_Order_Status_History__c> sosh = new List<Sales_Order_Status_History__c>();
    if(Trigger.isafter){
        for(Sales_Order__c  so : Trigger.new){
            if(so.Sales_Order_Status__c == 'Order Acknowledgement'){
                sosh.add(new Sales_Order_Status_History__c(Status__c = so.Sales_Order_Status__c, SO_No__c = so.Name,Record_Created_Date__c=so.createdDate,Last_Modified_Date__c=so.systemModStamp,Record_User__c=userinfo.getUserName()));   
                insert sosh;     
            }
            else if(so.Sales_Order_Status__c == 'Customer Inputs'){
                sosh.add(new Sales_Order_Status_History__c(Status__c = so.Sales_Order_Status__c, SO_No__c = so.Name,Record_Created_Date__c=so.createdDate,Last_Modified_Date__c=so.systemModStamp,Record_User__c=userinfo.getUserName()));   
                insert sosh;
            }
            else if(so.Sales_Order_Status__c == 'Scheduling'){
                sosh.add(new Sales_Order_Status_History__c(Status__c = so.Sales_Order_Status__c, SO_No__c = so.Name,Record_Created_Date__c=so.createdDate,Last_Modified_Date__c=so.systemModStamp,Record_User__c=userinfo.getUserName()));   
                insert sosh;
            }

}}}

Please help

Hi,

 

I got an error when executing the test method I wrote for a trigger. I saw many entries in the discussion boards about this, but no concrete answer and nothing I can make an abstraction and apply it to my problem.

 

 

I have a trigger where I create posts to a a specific group if the Opportunity is closed. The trigger looks like this:

 

trigger chatterUpdateTrigger on Opportunity (before update) {
	
	Id parentPostId = [SELECT Id 
					   FROM CollaborationGroup 
					   WHERE Name=:'All Group'].Id;
					   
	Id RecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Opportunity' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id RecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Opportunity' 
						AND DeveloperName=:'Record Type 2'].Id;
	
	List<FeedPost> listPosts = new List<FeedPost>();
	
    for (Opportunity opp: Trigger.new){
    	
    	//List<RecordType> listOppRecordTypes = [SELECT DeveloperName FROM RecordType WHERE Id=:opp.RecordTypeId AND DeveloperName=:'Record Type 2' AND DeveloperName=:'Record Type 2'];
    	Opportunity beforeUpdate = System.Trigger.oldMap.get(opp.Id);

    		if(opp.RecordTypeId == RecordType1){
    			
    			if(beforeUpdate.StageName != opp.StageName && opp.StageName=='We WON!'){
    				
    				FeedPost post = new FeedPost(ParentId= parentPostId,Body='The opportunity ' +beforeUpdate.Name+ ' with a value of '+beforeUpdate.Amount+'€ has been won!');            
	        		listPosts.add(post);
	        		
    			}
    		}else{
    			
    			if(opp.RecordTypeId == RecordType2){
			
					if(beforeUpdate.StageName != opp.StageName && opp.StageName=='We WON!'){
	    				
	    				FeedPost post = new FeedPost(ParentId=parentPostId,Body='The opportunity ' +beforeUpdate.Name+ ' with a value of '+beforeUpdate.Amount_Quotation_Price__c+'€ has been won!');            
		    			listPosts.add(post);
		        		
    				}
			
    			}
    		} 
	}
	
	try{
		
		insert listPosts;
		
	}catch(Exception ex){
		Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {'customer.service@myself.me'});
        mail.setSubject('Chatter Trigger ERROR');
        String body = 'This message was sent automatically from chatterUpdateTrigger from SF. \n'+
        'Apparently there was an error on the insertion of the Chatter Message. This is the exception: \n'+ex;  
        mail.setPlainTextBody(body);
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
	
}

 

And this is the test class:

 

@IsTest
 public class testChatterUpdateTrigger{
    
    static testMethod void testChatterUpdateTrigger(){

	
	
	Id RecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Account' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id RecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Account' 
						AND DeveloperName=:'Record Type 2'].Id;

							
						
	Account ac1 = new Account(RecordTypeId = RecordType1,
							  Name = 'Test Account 1',
							  CurrencyIsoCode = 'EUR',
							  Industry = 'Test',
							  Account_Type__c = 'Agent',
							  BillingCountry = 'UK',
							  BillingCity = 'London',
							  BillingStreet = 'Aleski 123');
	insert ac1;
	
	Account ac2 = new Account(RecordTypeId = RecordType2,
							  Name = 'Test Account 2',
							  CurrencyIsoCode = 'EUR',
							  Industry = 'Test',
							  Account_Type__c = 'Agent',
							  BillingCountry = 'UK',
							  BillingCity = 'London',
							  BillingStreet = 'Aleski 123');
	
	insert ac2;							  
							  	
	
	Account account1= [SELECT Id,
									 Name
							  FROM Account
							  WHERE Name =: 'Test Account 1'
							  LIMIT 1];

	Account account2= [SELECT Id,
								 Name
							  FROM Account
							  WHERE Name =: 'Test Account 2'
							  LIMIT 1];

	Id oppRecordType1= [SELECT Id 
								 FROM RecordType 
								 WHERE SOBJECTTYPE=:'Opportunity' 
								 AND DeveloperName=:'Record Type 1'].Id;
								 
	Id oppRecordType2= [SELECT Id 
						FROM RecordType 
						WHERE SOBJECTTYPE=:'Opportunity' 
						AND DeveloperName=:'Record Type 2'].Id;								  							  
	
	Opportunity oppRecType1= new Opportunity(RecordTypeId = oppRecordType1,
											 Name = 'Test 1',
											 AccountId = account1.Id,
											 CurrencyIsoCode = 'EUR',
											 Amount = 100,
											 CloseDate = system.today(),
											 StageName = 'Pre-Study');

	insert oppRecType1;
	
	Opportunity opRec1= [SELECT StageName
						   FROM Opportunity
						   WHERE Name =:'Test 1'
						   LIMIT 1];

	Opportunity oppRecType2= new Opportunity(RecordTypeId = oppRecordType2,
										 Name = 'Test 2',
										 AccountId = account2.Id,
										 End_Customer_Country__c = 'UK',
										 Industry__c = 'Auto',
										 CurrencyIsoCode = 'EUR',
										 Vehicle_Types_pick_several__c = 'Test',
										 No_of_Vehicles__c = 0,
										 Load_weight__c = 0,
										 Lifting_height_mm__c = 0,
										 Operating_Conditions__c = 'Outside',
										 Quotation_Price__c = 1000,
										 Scope__c = 'Other',
										 StageName = 'Pre-Study',
										 Quotation_valid_until__c = system.today(),
										 CloseDate = system.today(),
										 Navigation__c = 'Other');

	insert oppRecType2;
	
	Opportunity opRec2= [SELECT StageName
						  FROM Opportunity
						  WHERE Name = 'Test 2'
						  LIMIT 1];

	List<Opportunity> listOpp = new List<Opportunity>();
	listOpp.add(opRec1);
	listOpp.add(opRec2);
	
	Integer feedEntriesBefore = [SELECT COUNT() 
					   FROM CollaborationGroup 
					   WHERE Name=:'All Group'];

	test.startTest();					   

	oppKoti.StageName = 'We WON!';
	update opRec1;
	
	AGVopp.StageName = 'We WON!';
	update opRec2;
	
    Integer feedEntriesAfter = [SELECT COUNT()
						   		FROM CollaborationGroup
						   		WHERE Name=:'All Group'];

	system.assertNotEquals(feedEntriesBefore, feedEntriesAfter);
	
	test.stopTest();

	}
	
}

 And I got this error when executing tests:

 

System.DmlException: Update failed. First exception on row ' with id XXXXXXXXXXXXX: first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, chatterUpdateTrigger: excecution of BeforeUpdate ON LINE 115 -> that is the update of opRec1 in the test method.

 

Does anyone know exactly what is happening and why?