• Churchill19
  • NEWBIE
  • 0 Points
  • Member since 2009

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 15
    Replies
Hi,

I have a problem with my code below... when a update happens on the (Parent object) Invoice__c the trigger links all related (Child object) Inv_Item__c together as a lookup relationship. This works if i manual update a Parent record by my self it links all child records together.

below is a diagram to visual explain what i doing...

Before Trigger
 
Invoice 1
                Inv_item1                Inv_item2                Inv_item3                Inv_item4

After Trigger
 
Invoice 1
                Inv_item1   ------>    Inv_item2   ------>    Inv_item3   ------>    Inv_item4

But when i bulk the trigger i get the following error message
 
Update failed. First exception on row 4 with id a21R0000000LrddIAC; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria

When i go to debug this its trying to link the another Inv_item__c with another Invoice__c below diagram: - 

Invoice 1
                Inv_item1   ------>    Inv_item2   ------>    Inv_item3   ------>    Inv_item4

Invoice 2
                Inv_item1               Inv_item2               Inv_item3               Inv_item4

so if you look at the diagram above its trying to link Inv_item1 on Invoice 2 to Inv_item4 on Invoice 1.

Any ideas to help resolve this please?

thanks..

code is below: - 
 
trigger ChildJoin on Invoice__c (after update)


{
     
    Set<ID> par = new Set<ID>();
	List<Inv_item__c> child = new List<Inv_item__c>();
    List<Inv_item__c> child2 = new List<Inv_item__c>();
    
    for(Invoice__c inv1 : Trigger.new){
       
            par.add(inv1.Id);
        
    }
    List<Invoice__c> updateInv = [SELECT Id,(Select Id, Predecessor_item__c, IDNo__c from Invoice_Items__r)  FROM Invoice__c WHERE Id in :par];
 
    List<Inv_item__c> relatedItemsToUpdate = new List<Inv_item__c>();
	
				child = [SELECT ID,Due_Date__c, Invoice_ID__c 
                                                          FROM Inv_item__c
                                                          WHERE Invoice_ID__c IN :par
                                                          AND IDNo__c = 1];
				child2 = [SELECT ID,Due_Date__c, Invoice_ID__c 
                                                          FROM Inv_item__c
                                                          WHERE Invoice_ID__c IN :par
                                                          AND IDNo__c = 2];
    
    for (Invoice__c inv1 : updateInv){
        // Loop through each Related Invoice Item record
        for(Inv_item__c rd : inv1.Invoice_Items__r)
        {
		
		
          
			if(rd.IDNo__c == 2)
            
        {
        
            
            rd.Predecessor_item__c = child[0].id;
        
        }   
        
        if(rd.IDNo__c == 3)
            
        {
        
            
            rd.Predecessor_item__c = child2[0].id;
        	
        }
			
			
			
			
            relatedItemsToUpdate.add(rd);
        
    }
    
    }
    
    update relatedItemsToUpdate;
 }

 
Hi,

i have a parent object called Projects__c which has a one-many relation to stage__c (Which is the child - this is a master detail relation tp the parent) i have a field Next_Stage__c (on stage__c) with is a lookup to its self.

what i want to do is when there is a update on the Projects__c i want to link the following records on Child Object together: -


Project1
|  
|       |
|                |
|                        |
stage1 ------stage2 

 
Can anyone provide me with an example of how to do this please?

thanks...
Hi,

i know its possible to do this in a Rollup Summary but wonder if it can be done in apex code? i.e.

Child Records                     End Date
-------------------                      ----------------
child1                                 12/06/2015
child2                                  06/05/2015
child3                                 18/06/2015


so the code would update a date field on parent with the max(End_Date__c) of the child record which the result would be "18/06/2015".

Thanks,

Sean.
Hi all,

can anyone help with a example of test code so i can test the following batch code please?
 
global class BulkRecordDelete implements Database.Batchable<sObject> {

    
    global string obj;
    private string query = 'SELECT Id FROM ';

    global database.querylocator start(Database.BatchableContext BC) {
        query = query + obj;
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<sObject> ob = new List<sObject>();

        for(sObject s : scope) {
            ob.add(s);
        }
        delete ob;
    }
    
    global void finish(Database.BatchableContext BC) {
        
		if (ApplicationClass.BatchEmailsEnabled) {
	        Id userId = UserInfo.getUserId();
	        String notify = [select Email from User where Id = :userId].Email;
	        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	
	        mail.setToAddresses(new String[] {notify});
	        mail.setReplyTo('batch@acme.com');
	        mail.setSenderDisplayName('Batch Processing');
	        mail.setSubject('Batch Process Completed');
	        mail.setPlainTextBody('Bulk ' + obj + ' delete has completed');
	
	        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
		}
    }
}
Thanks...
 
Hi,

I have a button that once clicked it call for visualforce page to render as pdf and save it to a record which works in the sandbox...
i am trying to write test scrip for the following code but not sure how to.... can anyone start me off?

here is my button
 
{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")} 

{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")} 

/* call class and pass through parameters */ 

var ref = "{!Sales_Quality_Assessments__c.Id}"; 

var result = sforce.apex.execute("PdfGeneratorControllerTest1","savePdf1",{parentId:"{!Sales_Quality_Assessments__c.Id}"}); 



window.open('/apex/FormTest?scontrolCaching=1&id='+ref+'&scontrolCaching=1');
and for the class: - 
 
global class PdfGeneratorControllerTest1 {

  
  webservice static void savePdf1(string parentId) {

    PageReference pdf = Page.FormTest;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',parentId);
    // create the new attachment
    Attachment attach = new Attachment();
    
    // the contents of the attachment from the pdf
    Blob body;

    try {

        // returns the output of the page as a PDF
        body = pdf.getContentAsPDF();

    // need to pass unit test -- current bug    
    } catch (VisualforceException e) {
        body = Blob.valueOf('Error...');
    }

    attach.Body = body;
    // add the user entered name pdf.getContentAsPDF    
    attach.Name = 'Coaching Form'+parentid;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = parentId;
    attach.ContentType = 'application/pdf';
    
    insert attach;

    // send the user to the account to view results
    // return Apexpages.currentPage();
    // return new PageReference('/'+parentId);

    //   return Apexpages.currentPage();

  }

}
thanks....

 

Hi All,

 

wonder if anyone can help me out with a problem that i have when inserting a .CSV through Visualforce to opportunity... i have a Lookup field  : -

 

o.BrokerSalesAgent__c = inputvalues[4];

which need to link an custom object which contains existing records that i want to link to via the name of the record. I have managed to link this through by using the record ID on the .csv but i have a 3rd party that will not have access to record ID's.

 

when try to use the name of the record i get the following error message: - 

 

Visualforce Error

 


System.StringException: Invalid id: Sean Broker Team

Error is in expression '{!ReadFile}' in component <apex:commandButton> in page uploadop

 

 

Class.FileUploadOpp.ReadFile: line 33, column 1

 

I know that i have to write some code to search for the existing records (ID,Name) but not sure how to approach this?

 

the code below shows the inputvalues from my .csv file mapping them to the fields in the opportunity object. 

 

 

 

rowCount = 0;
        filelines = nameFile.split('\n');
        opptoupload = new List<Opportunity>();
        
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            rowCount = filelines.size() -1;
            Opportunity o = new Opportunity();
            o.RecordTypeId = inputvalues[0];
            o.Broker_Ref__c = inputvalues[1];
            o.Name = inputvalues[2];
            o.StageName = inputvalues[3];
            o.BrokerSalesAgent__c = inputvalues[4];
            o.AccountId = inputvalues[5];
            o.CloseDate = date.valueof(inputvalues[6]);

             opptoupload.add(o);
        }

 Can anyone point me in the right direction or help me with a example of how i can do this please?

 

thanks,

 

sean.

Hi all,

 

need your help...

 

i have the following trigger below,

 

trigger Sales_Manager_Trigger on BGB_Contract__c (before insert, before update) {

	Map <id,BGB_Contract__c> contracts = new Map <id, BGB_Contract__c>();

    for (BGB_Contract__c bgbContract : Trigger.new)
    {
		contracts.put(bgbContract.Renewal_Negotiators__c, bgbContract);
    }		   
	//Not to fire Trigger if user is equal to 'Sean Churchill'
	if (UserInfo.getName()<> 'Sean Churchill')

	{ 
		Map <Id, String> bseNameContractIdMap = new Map<Id, String>();
	   for(BGB_Sales_Employees__c bse: [select name from BGB_Sales_Employees__c where ID IN :contracts.keySet()]){
	   	bseNameContractIdMap.put(bse.name, bse.id);
	   }
	   
	   for(User u: [select ID from User where Name IN :bseNameContractIdMap.keyset()]){
	   	BGB_Contract__c contract = contracts.get(bseNameContractIdMap.get(u.name)); // this is the record that the triggered fired for, that matches your users name
	   	contract.sales_manager__c = u.id;
	   }
			
	}
}

 

 

 and i have written test code but cannot get it over the 75% test coverage but only able to get it to 70%... can any one help?

 

@isTest
private with sharing class Sales_Manager_Email_Test {

static testMethod void MyTestSalesManEma()
{
test.starttest(); 

    BGB_Contract__c testContractEmail = new BGB_Contract__c();
    
      
   
    testContractEmail.Account_Name__c = '0012000000SSw7l';
    testContractEmail.Feedback__c = 'Testing';
    testContractEmail.Renewal_Negotiators__c = 'a0H20000001oFrpEAE';
    testContractEmail.Contract_Spend__c = 110;   
    
    insert testContractEmail;
    
 	test.stoptest();  
    

}
}

 

 

I need to write some code to cover the code below as i not cover these lines: -

 

for(User u: [select ID from User where Name IN :bseNameContractIdMap.keyset()]){
	   	BGB_Contract__c contract = contracts.get(bseNameContractIdMap.get(u.name)); // this is the record that the triggered fired for, that matches your users name
	   	contract.sales_manager__c = u.id;

 Any help would be great...

 

Sean.

Hi All,

 

need you help with a trigger i have that is fired when the Contract.Renewal_Negotiators__c field is inserted or updated the trigger then populates the Sales_Employees__c field which is a lookup field to the User object.

 

The trigger works on a manual process but i had to put in the following code to allow me to update all records in the Contracts object : -

 

                //Not to fire Trigger if user is equal to 'Admin Name'
                if (UserInfo.getName()<> 'Admin name')

 

i am hitting the governer limits if i take off the above code... i know the logic is in correct and that i need to take this out of the for loop.

 

Problem is that i not sure how to amend my code below so i don't hit the limits... can someone help me by re-writing the code below so i don't hit the limiters?

 

Thanks.

 

Sean. 

 

 

 

 

trigger Sales_Manager_Trigger on Contract__c (before insert, before update) { for (Contract__c Contract : Trigger.new) { //Not to fire Trigger if user is equal to 'Admin Name' if (UserInfo.getName()<> 'Admin name') { Contract.Sales_Manager__c = null; List <Sales_Employees__c> arrRenNegs = new list <Sales_Employees__c>(); arrRenNegs = [select name from Sales_Employees__c where ID = :Contract.Renewal_Negotiators__c]; if (arrRenNegs.size()>0) { List <user> arrUsers = new List <user>(); arrUsers = [select ID from User where Name = :arrRenNegs.get(0).Name]; if (arrUsers.size()>0) { Contract.Sales_Manager__c = arrUsers.get(0).ID; } } } } }

 

Hi,

 

wonder if you could help with the code below? we have a trigger that works unitl it hit the 20 query limit. I know that the logic need to be done out the for loop but not sure how to code it... can anyone help?

104 trigger FieldVisitTrigger on Field_Visit__c (before update) { if(trigger.isUpdate){ for(Field_Visit__c fieldVisit : trigger.new){ system.debug('############# Field Visit Before Update Trigger'); system.debug('############# Field Visit Validated Field = ' + fieldVisit.Validated__c + '#############'); system.debug('############# Field Visit ID = ' + fieldVisit.Id); String errMsg=''; List <Group> postcode_group_set=new List <Group>(); // Initialise list to contain any matches List <Group> postcode_matches=new List <Group>(); // Process only if Validated and Unallocated if (fieldvisit.validated__c && fieldvisit.job_status__c=='New PDV') { // Check for Site Postcode if (fieldvisit.site_postcode__c==null) { fieldvisit.addError(' No Site Postcode - Unable to assign to queue'); } else { // Calculate postcode prefix name details String postcode_prefix=fieldVisit.Site_Postcode__c.toUpperCase().replaceAll(' ',''); postcode_prefix=postcode_prefix.replaceAll('[0-9][A-Z]{2}$',''); // e.g. B23 String postcode_region=postcode_prefix.replaceAll('[^A-Z]',''); // e.g B // Set starting postcode e.g. B23_postcode_group String postcode_group_name=postcode_prefix+ '_postcode_group'; // e.g. B23_postcode_group // Set selection criteria e.g. All B postcodes with B%_postcode_group String postcode_group_select= postcode_region + '%_postcode_group'; try { // Get postcode list of all possibles postcode_group_set = [select id, name from Group WHERE type='Regular' and name like :postcode_group_select]; // while there are no matches (and there is a group set to check) while (postcode_matches.isEmpty() && postcode_group_set.size()>0) { // Search possible groups adjusting current postcode name postcode_group_name=postcode_prefix+ '_postcode_group'; // iterate group set looking for matches to current name for (group grp : postcode_group_set) { if (grp.name.equals(postcode_group_name)) { postcode_matches.add(grp); } } if (postcode_prefix.equals(postcode_region)) { break; } // reduce prefix e.g. B23 to B2 postcode_prefix=postcode_prefix.replaceAll('[0-9]$',''); } // Error checking if (postcode_matches.size()>1) { errMsg+=' Postcode group "' + postcode_group_name + '" - Duplicate group found.'; } if (postcode_matches.size()==0) { errMsg+=' Postcode group "' + postcode_group_select + '" - Not found.'; } // Get queue id for postcode group List<GroupMember> pg_member = [select GroupId from GroupMember WHERE UserOrGroupId =:postcode_matches.get(0).id]; // Error checking if (pg_member.size()>1) { errMsg+=' Postcode group "' + postcode_matches.get(0).name + '" - Assigned to more than one queue or group.'; } if (pg_member.size()==0) { errMsg+=' Postcode group "' + postcode_matches.get(0).name + '" - Not assigned to queue.'; } if (!errMsg.equals('')) pg_member=null; // Force error if error message // Get queue using queue id Group region_queue; for (GroupMember gm : pg_member) { Group g=[select id, name from Group where type='Queue' and id=:gm.GroupId]; if (g<>null) { region_queue=g; break; } } // Assign record to queue fieldVisit.OwnerId=region_queue.id; System.debug('############# Field Visit Owner Id Updated to ' + fieldVisit.OwnerId); // Move on job status (so future record updates will not trigger) fieldvisit.job_status__c='Issued to Field'; system.debug('############# Field Visit Job Status = ' + fieldvisit.job_status__c); } catch (Exception e) { fieldvisit.addError(errMsg + ' [Error for Site Postcode "' + fieldVisit.Site_Postcode__c + '"]'); /* + ' prefix:'+postcode_prefix + ' grp name:' + postcode_group_name + ' select:'+postcode_group_select + ' matches:'+postcode_matches + ' grp set:' +postcode_group_set);*/ } } } } } }

 

Hi,

 

I am trying to work out how I can set up a Long Text Area field to be read only and editable? I want a user to enter comments and then save them into the field and lets say a few days the user what to add a update on the comments field but leaving the ones that they original enter i.e. so they don't over write the previous comment?

 

any suggestions?

 

Thanks,

 

Sean.

Hi,

i have a parent object called Projects__c which has a one-many relation to stage__c (Which is the child - this is a master detail relation tp the parent) i have a field Next_Stage__c (on stage__c) with is a lookup to its self.

what i want to do is when there is a update on the Projects__c i want to link the following records on Child Object together: -


Project1
|  
|       |
|                |
|                        |
stage1 ------stage2 

 
Can anyone provide me with an example of how to do this please?

thanks...

Hi All,

 

wonder if anyone can help me out with a problem that i have when inserting a .CSV through Visualforce to opportunity... i have a Lookup field  : -

 

o.BrokerSalesAgent__c = inputvalues[4];

which need to link an custom object which contains existing records that i want to link to via the name of the record. I have managed to link this through by using the record ID on the .csv but i have a 3rd party that will not have access to record ID's.

 

when try to use the name of the record i get the following error message: - 

 

Visualforce Error

 


System.StringException: Invalid id: Sean Broker Team

Error is in expression '{!ReadFile}' in component <apex:commandButton> in page uploadop

 

 

Class.FileUploadOpp.ReadFile: line 33, column 1

 

I know that i have to write some code to search for the existing records (ID,Name) but not sure how to approach this?

 

the code below shows the inputvalues from my .csv file mapping them to the fields in the opportunity object. 

 

 

 

rowCount = 0;
        filelines = nameFile.split('\n');
        opptoupload = new List<Opportunity>();
        
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
            rowCount = filelines.size() -1;
            Opportunity o = new Opportunity();
            o.RecordTypeId = inputvalues[0];
            o.Broker_Ref__c = inputvalues[1];
            o.Name = inputvalues[2];
            o.StageName = inputvalues[3];
            o.BrokerSalesAgent__c = inputvalues[4];
            o.AccountId = inputvalues[5];
            o.CloseDate = date.valueof(inputvalues[6]);

             opptoupload.add(o);
        }

 Can anyone point me in the right direction or help me with a example of how i can do this please?

 

thanks,

 

sean.

Hi All,

 

need you help with a trigger i have that is fired when the Contract.Renewal_Negotiators__c field is inserted or updated the trigger then populates the Sales_Employees__c field which is a lookup field to the User object.

 

The trigger works on a manual process but i had to put in the following code to allow me to update all records in the Contracts object : -

 

                //Not to fire Trigger if user is equal to 'Admin Name'
                if (UserInfo.getName()<> 'Admin name')

 

i am hitting the governer limits if i take off the above code... i know the logic is in correct and that i need to take this out of the for loop.

 

Problem is that i not sure how to amend my code below so i don't hit the limits... can someone help me by re-writing the code below so i don't hit the limiters?

 

Thanks.

 

Sean. 

 

 

 

 

trigger Sales_Manager_Trigger on Contract__c (before insert, before update) { for (Contract__c Contract : Trigger.new) { //Not to fire Trigger if user is equal to 'Admin Name' if (UserInfo.getName()<> 'Admin name') { Contract.Sales_Manager__c = null; List <Sales_Employees__c> arrRenNegs = new list <Sales_Employees__c>(); arrRenNegs = [select name from Sales_Employees__c where ID = :Contract.Renewal_Negotiators__c]; if (arrRenNegs.size()>0) { List <user> arrUsers = new List <user>(); arrUsers = [select ID from User where Name = :arrRenNegs.get(0).Name]; if (arrUsers.size()>0) { Contract.Sales_Manager__c = arrUsers.get(0).ID; } } } } }

 

Hi,

 

I am trying to work out how I can set up a Long Text Area field to be read only and editable? I want a user to enter comments and then save them into the field and lets say a few days the user what to add a update on the comments field but leaving the ones that they original enter i.e. so they don't over write the previous comment?

 

any suggestions?

 

Thanks,

 

Sean.