• SLockard
  • SMARTIE
  • 594 Points
  • Member since 2012

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

Hi, I am new to SF and Apex and I am in need to understand what I am doing wrong on this trigger...

 

I have an object TRXN that holds transactions records. Some ot them are loaded from a legacy system (via batch) which sends a field called Contract__c  This field lets me search on a MEMBER__c object the corresponding Member__c lookup field that should be updated on the TRXN.Member__c  lookup relationship field.

 

I have a method whithin MEMBER getMember() that returns an ID primitive type field with the lookup Id that should be updated on the TRXN.Member__c lookup field.  The following code should be accomplishing that simply task, however,  I am not even able to compile (thru force.IDE) the trigger. The error I get is the following:

 

Save Error: Illegal variable declaration: Trx.Member__c

 

on this statement:  if (trxMember != null) then Trx.Member__c = trxMember;

 

Follows the trigger:

 

trigger TrxnBatchLoad on TRXN__c (after insert) {

 

List<TRXN__c> oTxIt =

[SELECT  tx.Mrch_Contract__c, tx.Merchant__c, tx.Member__c

   FROM TRXN__c tx

   WHERE tx.id IN : Trigger.new 

   FOR UPDATE];

 

  for (TRXN__c Trx : oTxIt)   {

    id trxMember = Member.getMember(Trx.Mrch_Contract__c);

       if (trxMember != null) then Trx.Member__c = trxMember; 

       else {Trx.Member__c = null;

              }

    Update oTxIt;                  

    }

 }

 

The method getMember has the following:

 

public ID getMember(string mbContract) {

 ID mbMember = null;

 List<Member__c> M = [SELECT mb.Name, mb.Contract__c

               FROM Member__c mb WHERE mb.Contract__c =: mbContract LIMIT 1];

        mbMember = M[0].id;

        return mbMember;             

}

 

I have assumed the relatinship field (lookup) is just an ID primitive type that holds the id of the corresponding row whithin the related object and that I should be able to replace it if in need of.

 

I would appreciate any help on this. Thanks a lot!

 

 

 

 

 

 

  • July 17, 2013
  • Like
  • 0

I need to extract the area code from the Account Phone field. Luckily, I really only need the data on North American accounts, so I'm thinking I could remove all non-number fields and then extract characters depending on what it starts with (if 011, then char 4 to 6, if 1, then char 2 to 4, else char 1 to 3). That would catch most cases but I can't believe there isn't code already out there for doing this. I've been searching all over to no avail. Are there functions I'm unaware of that could help? Anyone know of a better way to do this? 

  • June 12, 2013
  • Like
  • 0

Hi,

 

I created a Batch Apex but I guess im using it wrong because I get the error:

 

System.Exception: Attempted to schedule too many concurrent batch jobs in this org

 

I have a trigger that when the field Team__c in Users is modified, I have to retrieve all the accounts from this user and update a field Area__c in the account.

 

This is the trigger code where I check if the field Team__c has changed and if changed, send it the the apex batch to update all the accounts:

 

trigger UpdateKAMandCommAreawhenModUser on User (after update) { 
	Set<id> ownerIds = new Set<id>();
    Map<id, User> owners = new Map<id, User>();
    for (Integer i=0;i<Trigger.new.size();i++){
    	if (Trigger.new[i].Team__c!=Trigger.old[i].Team__c){
           Database.executeBatch(new AccountAreaReassignment(Trigger.new[i].Team__c,Trigger.new[i].Id));

    }
}

 

And this is my batch:

 

global class AccountAreaReassignment implements Database.Batchable<sObject>{
    
    //Receiving Area and Id of the user
    String Area{get;set;}
    Id UserId{get;set;}
    global AccountareaReassignment(String Area,Id UserId){
        this.Area=Area;
        this.UserId=UserId;
    } 
global Database.QueryLocator start(Database.BatchableContext BC) { return DataBase.getQueryLocator([SELECT Id,Area__c FROM account WHERE OwnerId=:UserId]); } global void execute(Database.BatchableContext BC,List<Account> scopeAcc) { for (Integer i=0;i<scopeAcc.size();i++){ scopeAcc.get(i).Area__c=Area; } update scopeAcc; } global void finish(Database.BatchableContext BC) { //Send an email to the User after your batch completes Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'a.tejado@hotelbeds.com'}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Batch Job is done'); mail.setPlainTextBody('The batch Apex job processed '); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }

 

I want to change my code in order to send to the Batch the list of User Id's that have been modified. But then I dont know how to work with that list in the batch, could someone help please?

 

Thanks a lot!

 

Antonio

Hi all,

 

Just a quick one which I'm sure is really easy but I've been wracking my brains for a few hours on this one. 

 

I want to do an if function that would read along the lines of "If string x starts with string y".

 

Any help would be great!

 

Many thanks

 

Eran

  • November 20, 2012
  • Like
  • 0

I've tried a few variations and can't seem to get it right.

 

I need to pass a date from a custom object (Appliance__c) to a standard object (Entitlement).  There is a lookup field to the custom object from the entitlement object.

 

Date on the appliance is called "Latest_Check_In_Date__c" and the date on the Entitlement is called "first_check_in_date__c"

 

Any help would be greatly appreciated.

 

Here is the code I have so far which results in an error: Error:Apex trigger EvalFirstCheckIn caused an unexpected exception, contact your administrator: EvalFirstCheckIn: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: Trigger.EvalFirstCheckIn: line 16, column 1

 

trigger EvalFirstCheckIn on Appliance__c (before update, after insert) {

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

    for(Appliance__c App : Trigger.new)
    {
        Ids.add(app.id);
    }

List<Appliance__c> applist = new List<Appliance__c>([Select Id, latest_check_in_date__c FROM Appliance__c WHERE Id in :Ids]);

    for(Appliance__c temp : applist )
    {
        Entitlement ent = new Entitlement();
        ent.first_check_in_Date__c = temp.Latest_Check_In_Date__c;
        update ent;
    }

}

 

May be my brain is just not working this morning, but I am not sure how to do what I am looking at doing.  

for(Account_To_Import__c ai : [select id, name from Account_To_Import__c where Census_Import__c=:ApexPages.currentPage().getParameters().get('id')]){
        
            account a = [select id, name from account where ssn__c = :ai.ssn__c];
            if(a.id != ''){

 What I am trying to do is take one piece of information Account_to_import__c and compare it to the actual account. The first line " for(Account_To_Import__c ai :...." gets the original data.  Then for each object in that list I want to see if an account exists with the same SSN.  if it does I run one bit of code if it does not I run another bit of code.  The issue I am having is that when I run it if the account does not exist I get the error that the list has no rows for assignment.   How should I have this built?  Thanks for the help.

Hello, I am looking for some help with creating a trigger that will update a field named "Last Person Worked" on the contact based on the assigned user of the newest activity related to the contact. I am new to developing in general and though I wanted to tough this out and figure out for myself the need has become more critical. Any help would be greatly appreciated.

Hi Community,

 

My question here is when a trigger fires after how many soql quires or DML statemnets it will hit governor limits.

 

Thanks,

Suresh.

Hi Folks,

 

How to get the Apex class name of the batch job id in batch apex. can any one suggest me. this is very urgent..............pleaseeeee......................

 

thanks

krish

Hi,

 

I'm trying to write some batch apex for a basic field update.  The field update pulls the Payment_Type__c from Recon_Detail__c object to the Payment_Type__c field on the Actual__c object.  I'm relating to two by their Opportunity IDs.  I'm having issues instantiating my query to relate both objects together.  Here's the error:

 

Initial term of field expression must be a concrete SObject: String at line 15 column 133 (line underlined and colored in navy below)

 

Here's my code:

 

global class UpdatePaymentTypeonActual implements Database.Batchable<sObject>{
 
    //This is the query that is passed to the execute method.  It queries all of the Actuals that do not
    //have a Payment Type.
    
    String query = 'SELECT id, Opportunity__c, Payment_Type__c FROM Actual__c WHERE Payment_Type__c = null';
 
    global database.queryLocator start(Database.BatchableContext BC) {
        return database.getQueryLocator(query);
 
    } //close start method
 
    global void execute(Database.BatchableContext BC, List<Actual__c> scope) {
 
        List<Recon_Detail__c> reconDetails = [Select id, Opportunity__c, Payment_Type__c From Recon_Detail__c Where Opportunity__c=:query.Opportunity__c limit 1];
 
        // Iterate through the whole query of Actuals with blank Payment Types and insert Payment Type from the Recon Detail.
        for(Actual__c a : scope) {
            if(a.Payment_Type__c = null) {
                a.Payment_Type__c = reconDetails.Payment_Type__c;
            } //close if statement
        } //close for-loop
 
        try {
            update scope;
        } catch (system.dmlexception e) {
            System.debug('Scope not updated: ' + e);
        }
 
    } //close execute method
 
    global void finish(Database.BatchableContext BC) {
 
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            from AsyncApexJob where Id =
            :BC.getJobId()];
 
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
        mail.setToAddresses(new String[] {a.CreatedBy.Email});
        mail.setReplyTo('rachelbr@angieslist.com');
        mail.setSenderDisplayName('Salesforce');
        mail.setSubject('Payment Type Update ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems +
        ' batches with ' + a.NumberofErrors + ' failures.  Huzzah.');
 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
 
    } //close finish method
} //close class

 

I looked at the best practices page for bulkifying code here => http://wiki.developerforce.com/page/Apex_Code_Best_Practices  I cannot seem to get it right because I still get the error of too many SQL Queries.  Could someone please give me some direction as how to bulkify this trigger?

 

trigger UpdateProjectFromOpportunity on Opportunity (after update) {

for (opportunity theOpportunity : Trigger.new )  {  
    //Create an empty Tenrox Project List
List<tenrox__c> theTenroxProjects = new List<tenrox__c>();

For(tenrox__c theProject:[SELECT  id, KI_Project_Coordinator_pre_sales__c FROM tenrox__c WHERE opportunity__c = :theOpportunity.id AND KI_CAD_Project_Status__c  != 'Cancel' AND KI_CAD_Project_Status__c  != 'Complete' limit 25 ])
{
if (theOpportunity.Project_Coordinator__c != null ) {
theProject.KI_Project_Coordinator_pre_sales__c = theOpportunity.Project_Coordinator__c; 
}

theTenroxProjects.add(theProject);
} // End of For Loop for List

//Make sure there is something to update
if (!theTenroxProjects.isEmpty()) {
update theTenroxProjects;
} // End check for Records Processed

} // End of For Loop of Entire Trigger

} // End of Trigger

     

Hello,

I need help to create a triggers.

 

One Object: Opportunity

Other Object: Cases

 

Scenario: Cases has status "New, Sales, Closed". Cases is not related to opp but related to Accounts object.[Account and Opportunity are related] 

I have created a field on Opportunity and I want that whathever is the status of Case, it should populate on the Opportuity object in the field i  created.

Could you please tell me how to write a trigger based on the above scenario.

 

 

I tried writing  a trigger but am stuck that how to match the account ID to the account Id on case to get the case status.

But I need to update the filed on Opportunity and Opportunity laos has account name.

 

this is the relation

Case-> Account

Account-> Opp

 

 

trigger Updateopp on Opportunity (after insert,after update) {
list<Cases> ca = new list<Cases>();
for(Cases c:trigger.new)
{
list<Cases> caa = new list<Cases>();
ca = [select Status from Cases where id =: c.AccountId];

 

 

Please help!

SOQL returns 0 rows, and gives me System.ListException: List index out of bounds: 0

I thought  checking for null should get rid of the error, but no, it still errors out.

 

list<Object__c> obj = new list<Object__c>();

 

obj  =  [select ..........];

 

(if obj != null) {

 

      //get into this block

}

 

update obj[0] ;

 

Does SOQL always have to return some result?

  • September 25, 2012
  • Like
  • 0

I'm usinf a sandbox trying to run a query to get back all open cases that I will then iterate through and do some work on.  Here's my query:

 

SELECT CaseNumber, Status, IsClosed, IsDeleted, Owner.name, LastModifiedDate, Contact.name, Contact.Email FROM Case

 

In the Force.com Explorer, I get all the cases back, but when I run this in a class in my sandbox, I get no results (from the log output, that is).  The below example was a test with pulling from the Account table:

 

09:59:09.617 (1617692000)|SOQL_EXECUTE_BEGIN|[10]|Aggregations:0|select Name from Account
09:59:09.621 (1621556000)|SOQL_EXECUTE_END|[10]|Rows:0

 

I'm pretty sure I'm hitting the same database, and I seem to see this behavior all tables that I've spot checked.

 

Any ideas?

Hi, I am new to apex developpement

I get this message not sure I am allowed to do that but i need to create a list of lists to create dynamics columns

Thanks

 

public with sharing class modut3 {

 

public Class BoxItem{
....
}
}

public Class LineBoxItems{
public integer row {get;set;}
public string rowLabel {get;set;}
public list<boxItem> lRowBoxIt {get;set;}

public LineBoxItems(
integer r,
string rl ,
list<BoxItem>lb
) {
row=r;
rowLabel=rl;
lRowBoxIt=lb;
}
}

 


LBItems = new list<LineBoxItems>();
list <BoxItem> rowBoxItems = new list<BoxItem> ();

rowBoxItems.add(new BoxItem(r,c,...));

LBItems.add(r,'s', rowBoxItems);


i can not compile and get

Save error: Method does not exist or incorrect signature: [LIST<modut3.LineBoxItems>].add(Integer, String,
LIST<modut3.BoxItem>)

  • September 19, 2012
  • Like
  • 0

I have triggers attached to several objects for our group.

 

The creation of cloning of a top level object trickles down and clones everything associated with /that/ object. Easy enough.

 

but in that cloning of child objects other triggers are fired to perform this and that.. It seems I am hitting my sql query cap.

 

My question : Does the 100 query cap run /per/ trigger or is it cummulative of all processes run from the initial trigger?

 

 

  • September 13, 2012
  • Like
  • 0

I have a class that has some limited functionality. I'd like for it to be able to handle more related priorities without having to hard-code each scnario, e.g.:

 

List<Client_Priority__c> writePriority = new Client_Priority__c[6];
                   writePriority = [SELECT ClientCode__c, Priority_Notes__c, Status__c FROM Client_Priority__c
                                      WHERE Status__c = 'Active' AND Client_Priority__c.ClientCode__c =: cci.Id
                                      LIMIT 5];
                                       
                            //for(Client_Priority__c wp : writePriority){
                if(writePriority.size() == 1){
                                priorityList += 'Client Priorities: \r\n- ' + writePriority[0].Priority_Notes__c;
                                priorityList += '\r\n';
                }
                if(writePriority.size() == 2){
                                priorityList += 'Client Priorities: \r\n- ' + writePriority[0].Priority_Notes__c;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[1].Priority_Notes__c ;
                                priorityList += '\r\n';
                }
                if(writePriority.size() == 3){
                                priorityList += 'Client Priorities: \r\n- ' + writePriority[0].Priority_Notes__c;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[1].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[2].Priority_Notes__c ;
                }
                if(writePriority.size() >= 4){
                                priorityList += 'Client Priorities: \r\n- ' + writePriority[0].Priority_Notes__c;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[1].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[2].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[3].Priority_Notes__c ;
                }
                if(writePriority.size() >= 5){
                                priorityList += 'Client Priorities: \r\n- ' + writePriority[0].Priority_Notes__c;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[1].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[2].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[3].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[4].Priority_Notes__c ;
                }
                if(writePriority.size() >= 6){
                                priorityList += 'Client Priorities: \r\n- ' + writePriority[0].Priority_Notes__c;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[1].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[2].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[3].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[4].Priority_Notes__c ;
                                priorityList += '\r\n';
                                priorityList += '- ' + writePriority[5].Priority_Notes__c ;
                }

 

It prints text out too the client priorities field like this:

 

Client Priorities:

- A Priority

- Another Priority

- Foo Foo Foo

 

How could I get this to work in a loop to handle more than 6 (what I have coded for now) client priorities?

  • September 12, 2012
  • Like
  • 0

Hi Team,

 

Im new to salesfore, iam learning it, where I can get the perfect tutorials for apex classes and pages.

Please help.

 

Thanks,

Surya.

  • September 12, 2012
  • Like
  • 0

Hi everyone.  I have a trigger that currently works fine through the user interface.  However I need to bulk update 85,000 task records and the trigger is causing failures.

 

Intended trigger purpose:  Update the Last_SW_Activity__c field (date time field) on the account object with the last modified date of the record when a task record meets the following criteria:

  1. The Subject Line starts with "sw".
  2. The task is marked as completed.
trigger LastSWDate on Task (after insert, after update) {
 
  //To do - If the subject of a completed task contains "SW", put the date of the completed task in the 
  //the "Last_SW_Activity__c" field on the account object

//Create a set of related account ID's
Set <ID> acctIDs = new Set <ID> ();
//Create a list to hold the Updated Accounts
List<Account> updAccts = new List<Account>();

//For every task, add it's related to account ID to the set
  for (Task t: Trigger.new){
    acctIDs.add(t.accountID);
//Create a map to match the task related to ID's with their corresponding account ID's
    Map<ID, Account> acctMap = new Map<ID, Account> ([Select ID, Last_SW_Activity__c from Account where ID in :acctIDs]);
//Create the account object
      Account acctRec = acctMap.get(t.accountID);

//If the account ID isn't null, the subject line starts with "sw", and the task has been marked as completed    
  If ((t.accountID != null) &&(t.subject.indexOf('sw')==0) && (t.Status == 'Completed'))
//Check to see if the Last_SW_Activity__c field is current compared with the latest completed activity
      If (acctMap.get(t.accountID).Last_SW_Activity__c < t.LastModifiedDate || acctMap.get(t.accountID).Last_SW_Activity__c ==null){
//Update the Last_SW_Activity__c field on the account object with the task's end date  
        acctrec.Last_SW_Activity__c = t.LastModifiedDate;
        updAccts.add(acctrec);
    }
  }
  update updAccts;
}

 Can somebody please help make the trigger code more efficient (bulkifying it) and help with creating a test class?  I'm not a developer and could use some serious help here.  Thanks!!

 

 

  • September 11, 2012
  • Like
  • 0

The trigger below deletes related objects when our custom object tracking sales coverage - Coverage_person__c - is deleted.

It works fine in the web site, works ok on dataloader deletes in small bacthes of 1, or 5, but at higher numbers it fails. 

Here is the code:

 

trigger CPChatterandATMDeleterBulked on Coverage_Person__c (before delete) 
{

    List<string> AcctIds = new List<string>();
    List<string> useIds = new List<string>();
    
    for(Coverage_Person__c p:trigger.old) 
    {
        AcctIds.add(p.Account__c);
        useIds.add(p.User__c);
    }
        
    List<EntitySubscription> esSet= [select id from EntitySubscription where ParentId IN :AcctIds and subscriberid IN :useIds];
    List <AccountTeamMember> atmList = [select id from AccountTeamMember where  UserId IN :useIds and AccountId IN :AcctIds];
    
    
     for(Coverage_Person__c p:trigger.old) 
    {
    
        
        
        delete esSet;
        delete atmList;      
    }
    
}

 here is the error when i try to delete a list of 16 records:

 

"CPChatterandATMDeleterBulked: execution of BeforeDelete

caused by: System.DmlException: Delete failed. First exception on row 0 with id 0E8K0000000JnNNKA0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: []

Trigger.CPChatterandATMDeleterBulked: line 22, column 1"

 

However if I shorten the list to 5 records, that record does not produce any error.

Any thoughts?

Thanks

  • September 11, 2012
  • Like
  • 0

Hi, I am trying to make a forumla on the Contact which takes its accounts billing state and correctly sets it to the proper abbreviation. Here is my formula:

 

if(Account.BillingState <> null,
	UPPER(LEFT(Account.BillingState,1))+
	if(LEN(Account.BillingState) = 2,
		UPPER(RIGHT(Account.BillingState,1)),
	if(CONTAINS(Account.BillingState, ' '),
		UPPER(LEFT(RIGHT(Account.BillingState, FIND(' ', Account.BillingState)), 1)),
	if(BEGINS(UPPER(Account.BillingState), 'T')||UPPER(Account.BillingState) = 'NEVADA'||UPPER(Account.BillingState) = 'MISSISSIPPI'||UPPER(Account.BillingState) = 'MINNESOTA',
		UPPER(LEFT(RIGHT(Account.BillingState, 2), 1)),
	if(UPPER(Account.BillingState) = 'ARIZONA'||UPPER(Account.BillingState) = 'MONTANA',
		UPPER(LEFT(RIGHT(Account.BillingState, 3), 1)),
	if(UPPER(Account.BillingState) = 'ALASKA'||UPPER(Account.BillingState) = 'MISSOURI',
		UPPER(LEFT(RIGHT(Account.BillingState, 4),1)),
	if(BEGINS(UPPER(Account.BillingState),'W')||BEGINS(UPPER(Account.BillingState),'A')||BEGINS(UPPER(Account.BillingState),'N')||BEGINS(UPPER(Account.BillingState),'U')||BEGINS(UPPER(Account.BillingState),'O')||BEGINS(UPPER(Account.BillingState),'D')||BEGINS(UPPER(Account.BillingState),'F')||BEGINS(UPPER(Account.BillingState), 'ID')||BEGINS(UPPER(Account.BillingState), 'IN')||BEGINS(UPPER(Account.BillingState), 'IL'),
		UPPER(LEFT(RIGHT(Account.BillingState, 1), 1)),
	if(BEGINS(UPPER(Account.BillingState),'V')||BEGINS(UPPER(Account.BillingState),'P')||BEGINS(UPPER(Account.BillingState),'L')||BEGINS(UPPER(Account.BillingState),'K')||BEGINS(UPPER(Account.BillingState),'G')||BEGINS(UPPER(Account.BillingState),'H')||BEGINS(UPPER(Account.BillingState),'I'),
		UPPER(RIGHT(Account.BillingState, LEN(Account.BillingState)-1)),
	if(BEGINS(UPPER(Account.BillingState), 'C'),
		if(LEN(Account.BillingState) < 11,
			UPPER(LEFT(RIGHT(Account.BillingState, 1), 1)),
		UPPER(RIGHT(Account.BillingState, LEN(Account.BillingState)-1))),
	if(BEGINS(UPPER(Account.BillingState), 'MAI')||BEGINS(UPPER(Account.BillingState), 'MAR'),
		UPPER(RIGHT(Account.BillingState, LEN(Account.BillingState)-1)),
	UPPER(LEFT(RIGHT(Account.BillingState, 1), 1))))))))))),
'')

 The logic I used is a little weird because of the 5000 char limit, but if you see any issues with it let me know because it's not working correctly.

Thanks!

Hello everyone,

 

We are trying to use Beatbox and connect to salesfroce through a https connection with a proxy, but are getting an error: ssl.SSLError : EOF occured in violation of protocol .. Here is some of the code:

 

import os
import sys
import beatbox
import xmltramp
import datetime
import urllib

sf = beatbox._tPartnerNS
svc = beatbox.Client()
beatbox.gzipRequest=False

class BeatBoxDemo:

	def login(self, username, password):
		self.password = password
		loginResult = svc.login(username, password)
		
		return loginResult
		
		
demo = BeatBoxDemo()
loginResult = demo.login('username@website.com', 'passandsecuritytoken')

newPost = { "ParentID" : "groupIdHere", "Body" : "bodyText", "Type" : "TextPost", "type" : "FeedItem" }
r = svc.create(newPost)

if str(r[sf.success]) == 'true':
	print "success"
else:
	print "error"
print "error :" + str(r[sf.errors][sf.statusCode]) + ":" + str(r[sf.errors][sf.message])





# in beatbox 
class Client:
	def __init__(self):
		self.batchSize = 500
		self.serverUrl = "test.salesforce.com/services/Soap/u/21.0"
		self.__conn = None
		
		
def makeConnection(scheme, host):
	if forceHttp or scheme.upper() == 'HTTP':
		return httplib.HTTPConnection(host)
	user = 'username';passwd='password'
	#host='test.salesforce.com';port=443
	port=443
	phost='proxy.address.com';pport=80	
	user_pass=base64.encodestring(user+':'+passwd)
	user_pass=user_pass.replace('\n', '')
	proxy_authorization='Proxy-authorization: Basic '+user_pass+'\r\n'
	proxy_connect='CONNECT %s:%s HTTP/1.0\r\n'%(host,port)
	user_agent='User-Agent: python\r\n'
	proxy_pieces=proxy_connect+proxy_authorization+user_agent+'\r\n'
	proxy=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	proxy.connect((phost,pport))
	proxy.sendall(proxy_pieces)
	response=proxy.recv(8192)
	status=response.split()[1]
	#if status!=str(200): raise 'Error status=',str(status)
	sock=ssl.wrap_socket(proxy)
	f=httplib.HTTPConnection('localhost')
	f.sock=sock
	#f.Url=host
	print f
	return f
	
	

 If I change a few things around sometimes I also get an UNKNOWN EXCEPTION: destination url was not reset ..

Any help would be greatly appreciated!

Hi everyone,

 

I am getting a NullPointerException and I have no idea why. Here is a simplified version of the code:

global class batch_class  implements Database.Batchable < Sobject >
{

	global Id idOne; 
	global Id idTwo;
	global id idThree;
	global string query;
	
    global batch_class() {
    query='SELECT case.CreatedDate, case.Score__c, case.OwnerId, case.A_name__c, case.RecordTypeId, case.Origin FROM Case WHERE case.Origin = \'Email\' LIMIT 200';
    }
    
    global database.Querylocator start(Database.Batchablecontext ch) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.Batchablecontext ch, list<Case> list_Case) 
    {
		list<RecordType> list_rd=[select RecordType.Name, Id from RecordType where name=:'Name One' or name=:'Name Two'];
		for(RecordType loopRd:list_rd)
		{
			if(loopRd.Name=='Name One')
			{
				idOne=loopRd.Id;
			}else if(loopRd.Name=='Name Two')
			{
				idTwo=loopRd.ID;
			}
		}
		for(case loop_case:list_Case)
		{
			if(loop_case.RecordTypeId==idOne)
			{
				// do stuff .. 
			}
			else if(loop_case.RecordTypeId==idTwo)
			{
				if((loop_case.A_name__c=='Blah')||(loop_case.A_name__c=='One & Two')||(loop_case.A_name__c=='Another')||(loop_case.A_name__c=='Yes No'))
				{
					system.debug('>>Inside A case<>>> Agency name'+loop_case.A_name__c);
					loop_case.Score__c=loop_case.Score__c+2;
				}	 
			}
		}
	}  
    
    global void finish(Database.BatchableContext ch) {
        System.debug('<>>>>>>>>>>>>>>End >>>>>>>>>>>>>');
    }

}

 and the test case:

@isTest
private class batch_clas_TESTT {
    static testMethod void tClass() {

    User U = [SELECT Id FROM User WHERE Name = 'user U'];
     RecordType rType2 =[select Name, Id from RecordType where name='nameOne' LIMIT 1];
    RecordType rType1 =[select Name, Id from RecordType where name='nameTwo' LIMIT 1];
    List<Case> testCases = new List<Case>();
    
    Case caseR = new Case(Origin = 'Email', OwnerId=U.Id, Case_Type__c = 'blah', A_name__c = 'Blah', recordType = rType1, recordTypeId = rType1.Id);
    testCases.add(caseR);
    
    Case caseN = new Case(Origin = 'Email', OwnerId=U.Id, Case_Type__c = 'blah blah', A_name__c = 'Blah', recordType = rType2, recordTypeId = rType2.Id);
    testCases.add(caseN);
    
    insert testCases;
    
    Test.StartTest();
    
    batch_class bcs = new batch_class();
    Database.executeBatch(bcs, 200);
    
    Test.StopTest();    
    }
}

 I keep getting the null pointer exception for line 38, where it checks for case.A_name__c, however, I get to line 42 before it stops. I can see the debug statement at line 40, which debugs the correct value .. Any ideas? Thanks

Hi everyone,

 

We are currently trying to migrate our code to production, but this FATAL_ERROR|Internal Salesforce.com Error is stopping us.

Here is the code from the triggers that cause this error.

 

trigger triggerDNC on Contact (before insert, before update) 
{
	List<Contact> conList = new List<Contact>();
	List<String> accList = new List<String>();
	
	if (Trigger.isInsert)
	{
		for (Contact c : Trigger.new) 
		{
			boolean hasAccount = true;
			if (c.AccountId == null)
			{
				hasAccount = false;
			}
			else
			{
				conList.add(c);
				accList.add(c.AccountId);
			}
		}
		List<Account> checkAccList = new List<Account>();
		if (!accList.isEmpty())
		{
			checkAccList = 
				[SELECT Id, BillingState FROM Account WHERE Id IN :accList]; // this is where the error gets generated from !!!
			for (Account a : checkAccList)
			{
				// do stuff .. doesnt get here
			}
		}
	}
}

 

trigger LeadConversionTrigger on Lead (after insert,after update) {
    try{
    list<Lead> oldlead= Trigger.old;
    list<Lead> newLead=Trigger.new;       
    Account acc= new Account();
    RecordType rdc= new RecordType();
    rdc=[select Id, name from RecordType where RecordType.Name ='FromWeb' limit 1];
    map<id, id> map_OppCon_id = new map<id, id>();
    for(Lead LeadtoWork: newLead )
    {
        Database.Leadconvert lc= new Database.Leadconvert();
        lc.setLeadId(leadtoWork.Id);
        lc.setOverwriteLeadSource(true);
        lc.setConvertedStatus('Qualified');
        lc.setOpportunityName('Opportunity From Web');
        acc.RecordTypeId=rdc.Id;
        Database.Leadconvertresult lcr = Database.convertLead(lc);
        
        if(lcr.isSuccess())
        {
            // do stuff doesnt get here 
        }
        // do more stuff after, but doesnt get here
    }     
    } catch(Exception e){System.debug('exception is>>>>'+e);}  // goes to here after database.convertLead
}

 And here is the test that fails.

@isTest
private class TriggertestClass {
    static testMethod void myUnitTest() {
        Lead l1= new Lead();
        l1.LastName='lead';
        l1.FirstName='test';
        l1.Company='test comapny';
        l1.Status='Open';
        l1.OwnerId='111111111111111';
        l1.LeadSource='Webdialer';
        insert l1;
    }
}

 Here is the full description of the error from the debug log:

08:50:48.076 (1076907000)|SOQL_EXECUTE_BEGIN|[94]|Aggregations:0|select Id, BillingState from Account where Id IN :tmpVar1
08:50:48.078 (1078686000)|FATAL_ERROR|Internal Salesforce.com Error

08:50:48.078 (1078908000)|CODE_UNIT_FINISHED|triggerDNC on Contact trigger event BeforeInsert for [new]
08:50:48.090 (1090919000)|FATAL_ERROR|Internal Salesforce.com Error
08:50:48.097 (1097238000)|DML_END|[33]
08:50:48.097 (1097393000)|EXCEPTION_THROWN|[33]|System.DmlException: ConvertLead failed. First exception on row 0; first error: UNKNOWN_EXCEPTION, An unexpected error occurred. Please include this ErrorId if you contact support: ---: []

 

Any help would be greatly appreciated.

For a contact, you can click on the email field to send an email to that email address, and that functionality is automatically there. I want to know if there is a way to have that field become un click-able (as in you can't click it to send an email to that email address) when the Email Opt Out field is true. Does anyone know if that is possible?

Hi, I can' t get a simple SOQL query to work, which tries to get all the contacts from a certain account.

Here is my sample code:

 

trigger triggerDNC on Contact (before update) 
{
    //Assign the context before and after the change into a Map
    Map<Id,Contact> newContactMap = Trigger.newMap;
    Map<Id,Contact> oldContactMap = Trigger.oldMap;

    //Loop through the map
    for(Id contactId:newContactMap.keySet())
    {
         Contact myNewContact = newContactMap.get(contactId);
         Contact myOldContact = oldContactMap.get(contactId);
		 
		 // myNewContact.Account.Name DOESNT WORK HERE ?
		 
		 List<Contact> cons= 
              [SELECT Contact.Name, Contact.Phone, Contact.DoNotCall, Contact.Account.Name FROM Contact
                   WHERE Contact.Id!= :myNewContact.Id
                   AND Contact.Account.Id = :myNewContact.Account.Id]; // this doesnt filter out correctly
                         
               for (Contact con: cons) 
               {
                   // con.Account.Name WORKS HERE !!?
               }
                
               update cons;
	} 
}

 I can't access myNewContact.Account.Name or myNewContact.Account.Id, so I can't find a way to get only the contacts from the same account as the one in the trigger.

Any help / feedback would  be greatly appreciated .. thanks.

Hi, I am trying to make a forumla on the Contact which takes its accounts billing state and correctly sets it to the proper abbreviation. Here is my formula:

 

if(Account.BillingState <> null,
	UPPER(LEFT(Account.BillingState,1))+
	if(LEN(Account.BillingState) = 2,
		UPPER(RIGHT(Account.BillingState,1)),
	if(CONTAINS(Account.BillingState, ' '),
		UPPER(LEFT(RIGHT(Account.BillingState, FIND(' ', Account.BillingState)), 1)),
	if(BEGINS(UPPER(Account.BillingState), 'T')||UPPER(Account.BillingState) = 'NEVADA'||UPPER(Account.BillingState) = 'MISSISSIPPI'||UPPER(Account.BillingState) = 'MINNESOTA',
		UPPER(LEFT(RIGHT(Account.BillingState, 2), 1)),
	if(UPPER(Account.BillingState) = 'ARIZONA'||UPPER(Account.BillingState) = 'MONTANA',
		UPPER(LEFT(RIGHT(Account.BillingState, 3), 1)),
	if(UPPER(Account.BillingState) = 'ALASKA'||UPPER(Account.BillingState) = 'MISSOURI',
		UPPER(LEFT(RIGHT(Account.BillingState, 4),1)),
	if(BEGINS(UPPER(Account.BillingState),'W')||BEGINS(UPPER(Account.BillingState),'A')||BEGINS(UPPER(Account.BillingState),'N')||BEGINS(UPPER(Account.BillingState),'U')||BEGINS(UPPER(Account.BillingState),'O')||BEGINS(UPPER(Account.BillingState),'D')||BEGINS(UPPER(Account.BillingState),'F')||BEGINS(UPPER(Account.BillingState), 'ID')||BEGINS(UPPER(Account.BillingState), 'IN')||BEGINS(UPPER(Account.BillingState), 'IL'),
		UPPER(LEFT(RIGHT(Account.BillingState, 1), 1)),
	if(BEGINS(UPPER(Account.BillingState),'V')||BEGINS(UPPER(Account.BillingState),'P')||BEGINS(UPPER(Account.BillingState),'L')||BEGINS(UPPER(Account.BillingState),'K')||BEGINS(UPPER(Account.BillingState),'G')||BEGINS(UPPER(Account.BillingState),'H')||BEGINS(UPPER(Account.BillingState),'I'),
		UPPER(RIGHT(Account.BillingState, LEN(Account.BillingState)-1)),
	if(BEGINS(UPPER(Account.BillingState), 'C'),
		if(LEN(Account.BillingState) < 11,
			UPPER(LEFT(RIGHT(Account.BillingState, 1), 1)),
		UPPER(RIGHT(Account.BillingState, LEN(Account.BillingState)-1))),
	if(BEGINS(UPPER(Account.BillingState), 'MAI')||BEGINS(UPPER(Account.BillingState), 'MAR'),
		UPPER(RIGHT(Account.BillingState, LEN(Account.BillingState)-1)),
	UPPER(LEFT(RIGHT(Account.BillingState, 1), 1))))))))))),
'')

 The logic I used is a little weird because of the 5000 char limit, but if you see any issues with it let me know because it's not working correctly.

Thanks!

I am new to salesforce development and having an issue with this error. The code compiles fine and has no errors however, when trying to save a product i get this error:

 

" RevenueProject2: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object:

Trigger.RevenueProject2: line 58, column 1 "

 

Aim of project is to search for keywords ( all myString varaibles) in the product name and then copy the sales price to a a field in the RevenueObject. Along with that, I also have a field set up for all products that gives a running counter on the number of entries for each product.

 

The error is on this line: i = rO.FieldA__c;

 

Here is my code:

 

trigger RevenueProject2 on Opportunity (after insert, after update) {

String myString1 = '/test1';
String myString2 = '/test2';
String myString3 = 'test3';
RevenueObject__c rO;
double i;
decimal j= 0.00;

 // This is to create a list of all product names 
 List<OpportunityLineItem>   Product = 
        [Select CustomProductName__c, UnitPrice
         from OpportunityLineItem 
         where Opportunity.StageName != 'Closed Lost' 
         ]; 
        
    // The for loop is to go through each  product name and to categorize product types     
    for(OpportunityLineItem prdct: Product) {

		if(prdct.CustomProductName__c.contains(myString1)) 
        {
        	i = rO.FieldA__c; 
        	i++;                       //Updates Counter
        	rO.FieldA__c = i;           // Assigns counter to field  
        	j = prdct.UnitPrice;
        	rO.FieldB__c += j;
        	
        }
        else
        if(prdct.CustomProductName__c.contains(myString2))
        {
                i = rO.FieldC__c;  
        	i++;                        //Updates Counter
        	rO.FieldC__c = i;          // Assigns counter to field  
        	j = prdct.UnitPrice;
        	rO.FieldD__c += j;
        	
        }
        else
        if(prdct.CustomProductName__c.contains(myString3)) 
        {
        	i = rO.FieldE__c;
        	i++;                       //Updates Counter
        	rO.FieldE__c = i;         // Assigns counter to field  
        	j = prdct.UnitPrice;
        	rO.FieldF__c += j;
        	
        }
	else
        if(prdct.CustomProdName__c.contains(myString4)) 
        {
        	i = rO.FieldG__c;
        	i++;                        //Updates Counter
        	rO.FieldG__c = i;          // Assigns counter to field  
        	j = prdct.UnitPrice;
        	rO.FieldH__c += j;
        	
        }

    }
}

 

 

Hi, I am new to SF and Apex and I am in need to understand what I am doing wrong on this trigger...

 

I have an object TRXN that holds transactions records. Some ot them are loaded from a legacy system (via batch) which sends a field called Contract__c  This field lets me search on a MEMBER__c object the corresponding Member__c lookup field that should be updated on the TRXN.Member__c  lookup relationship field.

 

I have a method whithin MEMBER getMember() that returns an ID primitive type field with the lookup Id that should be updated on the TRXN.Member__c lookup field.  The following code should be accomplishing that simply task, however,  I am not even able to compile (thru force.IDE) the trigger. The error I get is the following:

 

Save Error: Illegal variable declaration: Trx.Member__c

 

on this statement:  if (trxMember != null) then Trx.Member__c = trxMember;

 

Follows the trigger:

 

trigger TrxnBatchLoad on TRXN__c (after insert) {

 

List<TRXN__c> oTxIt =

[SELECT  tx.Mrch_Contract__c, tx.Merchant__c, tx.Member__c

   FROM TRXN__c tx

   WHERE tx.id IN : Trigger.new 

   FOR UPDATE];

 

  for (TRXN__c Trx : oTxIt)   {

    id trxMember = Member.getMember(Trx.Mrch_Contract__c);

       if (trxMember != null) then Trx.Member__c = trxMember; 

       else {Trx.Member__c = null;

              }

    Update oTxIt;                  

    }

 }

 

The method getMember has the following:

 

public ID getMember(string mbContract) {

 ID mbMember = null;

 List<Member__c> M = [SELECT mb.Name, mb.Contract__c

               FROM Member__c mb WHERE mb.Contract__c =: mbContract LIMIT 1];

        mbMember = M[0].id;

        return mbMember;             

}

 

I have assumed the relatinship field (lookup) is just an ID primitive type that holds the id of the corresponding row whithin the related object and that I should be able to replace it if in need of.

 

I would appreciate any help on this. Thanks a lot!

 

 

 

 

 

 

  • July 17, 2013
  • Like
  • 0

I need help building a trigger on my customer object called Vendor Relationship.  WHen a user changes the status to Declined and the Declined Reason code to one of the Pickvalues.  I want the trigger to auto Share the record with one of my Salesforce to Salesforce Connections. 

 

 

HI all,

 

I've just spent the last four hours attempting to write and test my first trigger.  We have a custom object Health Check that has a Master-Detail relationship to Accounts.  We instantiate a new HC record ~3 months.  We want to copy the notes from the previous HC to the new one.  I have taken a clicks & code approach to this. I am looking for hope on my code, but if there is a better way to approach this whole effort, I'm certainly open.

 

On the Health Checks object, I have a "Date Conducted" field and a rich text field (I know, but my users insisted) called "Health Check Notes." I also have an Account__c field, which contains the parent Account's ID.

On Accounts, I have a "Last Health Check Conducted" field and a "Health Check Notes" field (also a RTF).

 

I have a WFR that fires when a new Health Check is created or edited.  If "Date Conducted" >= "Last Health Check Conducted" (also covers my users editing their notes after the call as issues are resolved), I copy the contents of the Health Check Notes field from the child Health Check object to the parent Account.  That's tested and working.

 

Next, when a new HC is created, I need to copy the contents from the parent Account into the new HC record.  Since WFR won't go parent->child, I did some research and wrote a trigger:

 

trigger populateHealthCheckNotes on Health_Check__c (after insert){
  
    Map<Id,Account> accounts = new Map<Id,Account>
    ([select ID, Health_Check_Notes__c from Account where Id IN :trigger.newMap.keySet()]);
  
    for(Health_Check__c hc : trigger.new){
         if(hc.Account__c != null){
         hc.Health_Check_Notes__c = accounts.get(hc.Account__c).Health_Check_Notes__c;    
          }
    }   
 
}

 

 

 

I wrote a Test Class to go with this:

@isTest 
private class testPopulateHealthCheckNotesTrigger {
  static testMethod void testNotePopulation()  {
    Account testAccount = new Account(Health_Check_Notes__c = 'Negotiating',Name = 'test Name');
    insert testAccount;
    Health_Check__c testHealthCheck = new Health_Check__c(Account__c = testAccount.ID);

Test.startTest();
insert testHealthCheck;
Test.stopTest();
system.assert(testHealthCheck.Health_Check_Notes__c == testAccount.Health_Check_Notes__c);
}

}

 

 

 

However, I'm getting this error:

 

Time Started 6/25/2013 11:52 AM Class testPopulateHealthCheckNotesTrigger Method Name testNotePopulation Pass/Fail Fail Error Message System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, populateHealthCheckNotes: execution of AfterInsert

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

Trigger.populateHealthCheckNotes: line 8, column 1: [] Stack Trace Class.testPopulateHealthCheckNotesTrigger.testNotePopulation: line 9, column 1

 

I'm pretty sure I'm doing something wrong and it has to do with grabbing the account ID and making sure I'm copying the right information, but I'm not sure where/how I'm going wrong exactly.  I need this to work, as I have a similar copy-and-paste exercise to do with two other fields, but trying to start small and stay on sure footing here.

 

All help greatly appreciated.

 

I need to extract the area code from the Account Phone field. Luckily, I really only need the data on North American accounts, so I'm thinking I could remove all non-number fields and then extract characters depending on what it starts with (if 011, then char 4 to 6, if 1, then char 2 to 4, else char 1 to 3). That would catch most cases but I can't believe there isn't code already out there for doing this. I've been searching all over to no avail. Are there functions I'm unaware of that could help? Anyone know of a better way to do this? 

  • June 12, 2013
  • Like
  • 0

Hi,

I have a doubt.

When i have to use an id which is the best way to put it in a variable.

 

user u=[Select id,name from user where... limit 1 ];
        post.CreatedById=u.id;

 

 

or

 

  post.CreatedById='005E0000003XNVp';

 

are there other way?

Which is the best practise?

 

Thanks in advantage.

BR

 

 

  • June 07, 2013
  • Like
  • 0

Hi Everyone ,

                       i have two fields (field1,field2) and i need to remove all non numeric characters from field1 and has to store the remaining numeric data  in field2 how can i achieve this....suggest me in this regard

I'm in the process of learning how to develope with Apex and I have a question about a test I'm trying to write for a trigger. I'm finding both don't have any syntax errors or anything but the test has 0% coverage of the trigger. The trigger is pretty basic, based on a status (I have a query for this) update a lookup field (rs_BM__c) with the same record as another lookup field (Enrollment_Manager__c) on the same table (Lead). Here is my Trigger code:

 

trigger SetBMForTransition on Lead (after update, after insert) {
	for(Lead a : [SELECT Id, Associate_Status__c, rs_BM__c from Lead
					WHERE (Associate_Status__c = 'Pending'
					OR Associate_Status__c='Enrolled' )
					AND rs_BM__c = null] )
					{a.rs_BM__c=a.Enrollment_Manager__c;}
}

 Here is my test code:

@isTest
private class SetBMForTransitionTriggerTest {

    static testMethod void pendingAndNull() {

		//instantiate the data
        List<Lead> inquiries = new List<Lead>();
        My_Biz_Office_User__c a = new My_Biz_Office_User__c();
        a.name='Sara Conde';
        My_Biz_Office_User__c b = new My_Biz_Office_User__c();
        b.name='Nicolette Taylor';
        insert a;
        insert b;	
        for (Integer i = 1; i <=20; i++){
        	inquiries.add(new Lead(FirstName='Test'
        						  ,LastName='Inquiry' + i
        						  ,Enrollment_Manager__c=b.id
        					      ,Status='Inquiry'));
        }
        for(Lead newInquiry : [SELECT id, name, Enrollment_Manager__c, Status
        					   FROM Lead
        					   WHERE Id
        					   IN :inquiries]){
					      		  	insert(newInquiry);
        					   }

		//update the data
        for(Lead change : [SELECT id, name, Enrollment_Manager__c, rs_BM__c, Status 
        				   FROM Lead
        				   WHERE Id
         				   IN :inquiries]){
        					  	change.Status='Pending';
      	}
        for(Lead newInquiry : [SELECT id, name, Enrollment_Manager__c, Status
        					   FROM Lead
        					   WHERE Id
        					   IN :inquiries]){
					      		  	update(newInquiry);
        					   }

		//test the data
        for(Lead updated : [SELECT id, name, Enrollment_Manager__c, rs_BM__c 
        					FROM Lead
        					WHERE Id
        					IN :inquiries]){
                				System.assertEquals(updated.rs_BM__c,updated.Enrollment_Manager__c);
    	}
}
}

 Thanks in advance - any help would be appreciated

Hi,

I am new to salesforce and i have to write trigger on custom object"Prod" and they purpose of that trigger is that when user enter data in field then its should update two more fields upon saving the record.

here is the example:

custom object = Prod

field 1 = field (this is text field)

field 2 = pick list field(option that should be populate is App)

field 3 = field(this text field)

if user enter in field 1 then its should poulate the field 2 = app and update the same value in field 3 = field 1.

please help me 

thanks

 

  • December 06, 2012
  • Like
  • 0

Hi all,

 

I am new to apex trigger i have a situation here and hoping for your quick response.

 

i have two custom objects here Exercise__c and Trainee__c, in Exercise__c i have a field of exercise1(number), exercise2(number)exercise3(number), exercise name and a lookup field of trainee name in Trainee__c object while in the Trainee__c i have a fields of trainee name and status(picklist).

 

i want to validate the 3 fields in the Exercise__c if the sum of 3 fields is less than 75 the status picklist field in Trainee__c will update to Fail and if it isgreater than 75 it will update to Pass.

 

 

Thank.

Hi,

 

I created a Batch Apex but I guess im using it wrong because I get the error:

 

System.Exception: Attempted to schedule too many concurrent batch jobs in this org

 

I have a trigger that when the field Team__c in Users is modified, I have to retrieve all the accounts from this user and update a field Area__c in the account.

 

This is the trigger code where I check if the field Team__c has changed and if changed, send it the the apex batch to update all the accounts:

 

trigger UpdateKAMandCommAreawhenModUser on User (after update) { 
	Set<id> ownerIds = new Set<id>();
    Map<id, User> owners = new Map<id, User>();
    for (Integer i=0;i<Trigger.new.size();i++){
    	if (Trigger.new[i].Team__c!=Trigger.old[i].Team__c){
           Database.executeBatch(new AccountAreaReassignment(Trigger.new[i].Team__c,Trigger.new[i].Id));

    }
}

 

And this is my batch:

 

global class AccountAreaReassignment implements Database.Batchable<sObject>{
    
    //Receiving Area and Id of the user
    String Area{get;set;}
    Id UserId{get;set;}
    global AccountareaReassignment(String Area,Id UserId){
        this.Area=Area;
        this.UserId=UserId;
    } 
global Database.QueryLocator start(Database.BatchableContext BC) { return DataBase.getQueryLocator([SELECT Id,Area__c FROM account WHERE OwnerId=:UserId]); } global void execute(Database.BatchableContext BC,List<Account> scopeAcc) { for (Integer i=0;i<scopeAcc.size();i++){ scopeAcc.get(i).Area__c=Area; } update scopeAcc; } global void finish(Database.BatchableContext BC) { //Send an email to the User after your batch completes Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {'a.tejado@hotelbeds.com'}; mail.setToAddresses(toAddresses); mail.setSubject('Apex Batch Job is done'); mail.setPlainTextBody('The batch Apex job processed '); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }

 

I want to change my code in order to send to the Batch the list of User Id's that have been modified. But then I dont know how to work with that list in the batch, could someone help please?

 

Thanks a lot!

 

Antonio

Hi Team,

 

I am using below trigger to update price filed from Product Shipper to DsP Product. It is working fine for new records but if change the price in product shipper then the value is updating but total amount is not getting exactly. this price field is using in workflow to calcuate the total amount.

 

trigger UpdatePrice on DSP_Product__c (before insert, before update) {
        
        set<String> years = new set<String>();
        set<Id> accounts = new set<Id>();
        map<String, Id> prevYearKeyDspMap = new map<String, Id>();
for(DSP_Product__c dspr : trigger.new){
            accounts.add(dspr.Account__c);
            years.add(dspr.Name);
                    }

Map<ID, Product_Shipper__c> psMap =
        new Map<ID, Product_Shipper__c>(
            [SELECT Price__c, Pack_Size__c
            FROM Product_Shipper__c
            WHERE Active__c = true]);
for ( DSP_Product__c dspp : trigger.new ) {
        if (prevYearKeyDspMap.size()>0){
            Product_Shipper__c ps = psMap.get(dspp.Product_Shipper__c);
            if ( ps != null ) {
                dspp.Product_Price__c = ps.Price__c;
                dspp.Product_Size__c = ps.Pack_Size__c;
            }
        }
    }
}

  • November 27, 2012
  • Like
  • 0
trigger CaseTrigger on Case (before update,before insert,before delete, after update, after insert, after delete)
{
     Profile p = [SELECT Name FROM Profile WHERE ID =:UserInfo.getProfileId()];
          if(p.Name != 'System Administrator') 
          {
               if (Trigger.isInsert && Trigger.isbefore)
                { 
                }
               if (Trigger.isUpdate && Trigger.isbefore)
                {
                     CaseFunctions.CaseValidationBeforeComplete(Trigger.oldMap, Trigger.newMap);
                } 
               if (Trigger.isDelete && Trigger.isbefore)
                {
                }
               if (Trigger.isInsert && Trigger.isafter)
                { 
                }
               if (Trigger.isUpdate && Trigger.isafter)
                {
                } 
               if (Trigger.isDelete && Trigger.isafter)
                {
                }
          }
              
}

 Above is a quick query to find out if the current user is a System Administrator.  Now what I also need to do is check to see if a specific manager assigned to the user.  So it would be equal to saying anyone that has a System Administrator as a manager....  Any ideas???

 

Thank you,

Steve Laycock

Hi all,

 

Just a quick one which I'm sure is really easy but I've been wracking my brains for a few hours on this one. 

 

I want to do an if function that would read along the lines of "If string x starts with string y".

 

Any help would be great!

 

Many thanks

 

Eran

  • November 20, 2012
  • Like
  • 0

I've tried a few variations and can't seem to get it right.

 

I need to pass a date from a custom object (Appliance__c) to a standard object (Entitlement).  There is a lookup field to the custom object from the entitlement object.

 

Date on the appliance is called "Latest_Check_In_Date__c" and the date on the Entitlement is called "first_check_in_date__c"

 

Any help would be greatly appreciated.

 

Here is the code I have so far which results in an error: Error:Apex trigger EvalFirstCheckIn caused an unexpected exception, contact your administrator: EvalFirstCheckIn: execution of BeforeUpdate caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []: Trigger.EvalFirstCheckIn: line 16, column 1

 

trigger EvalFirstCheckIn on Appliance__c (before update, after insert) {

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

    for(Appliance__c App : Trigger.new)
    {
        Ids.add(app.id);
    }

List<Appliance__c> applist = new List<Appliance__c>([Select Id, latest_check_in_date__c FROM Appliance__c WHERE Id in :Ids]);

    for(Appliance__c temp : applist )
    {
        Entitlement ent = new Entitlement();
        ent.first_check_in_Date__c = temp.Latest_Check_In_Date__c;
        update ent;
    }

}

 

Hi All,

 

I try to send the param from Visualforce page to my controller I just want to deleted my record from list

 

 

List has no rows for assignment to SObject

Error is in expression '{!removePayment}' in component <apex:page> in page welcomecustomerportal


An unexpected error has occurred. Your development organization has been notified.

 

My Visualforce Page:

<apex:repeat value="{!lstAuthContacts}" var="AC">
  <apex:outputField value="{!AC.Name}"/>
  <apex:outputField value="{!AC.Contact_Type__c}"/>
   
  <apex:form>
   <apex:commandLink value="Remove" action="{!removeContact}">
    <apex:param name="delContact" value="{!AC.Id}" assignTo="{!cParam}"></apex:param>
   </apex:commandLink>
  </apex:form>

 

My Controller:

 

public class AccountProfileController {

    public list<Contact> lstAuthContacts{get;set;}
	public AccountProfileController(){
		getlstAuthContacts();			
	}    
	public void getlstAuthContacts(){    	
    	lstAuthContacts = [Select	Contact.Id,
                                        Contact.Name,
                                        Contact.Contact_Type__c,
                           From	        Contact
                           Where	Contact.AccountId = ::ApexPages.currentPage().getParameters().get('id')
                           And		Contact.Contact_Type__c = 'Authorized Contact'];
    	
    }

    public string cParam{get; set;}
    public PageReference removeContact(){
    	if(cParam != null || cParam != ''){
        Contact contact = [select Id from Contact where id=:cParam];            
        delete contact; 
    	}else{
    		system.assertEquals('removeContact', 'ContactId = '+cParam);
    	}    
        return null;
    }    
}

 

It's work, my record is deleted but on visualforce is Show the error around 5 minute, after that I refresh agian it work agian

 

What going on?

 

 

Hi all,

 

I'm writing a class that performs some simple arithmetic based on opportunity probabilities to get the average probability of all that owner/account/product's opportunities. My class takes some IDs and strings, and I want it to create lists based on these input arguments, but keep getting the "unexpected token" error. Here's a snippet of the code:

 

public class ForecastFunction {
	public static double getProbability(ID own, ID acc, String product, String division){
    	double estimate = 0;
        List<Opportunity> a = [select Probability from Opportunity where OwnerID := own];
        for(integer i = 0;i<a.size();i++){
            estimate+=a[i].Probability/a.size();
        }
        return estimate;
    }
}

 Where "own" is my unexpected token (both with and without the colon). What am I doing wrong? This should be bread and butter, but that error is crippling, and, to me, unobvious.

 

Any help you can offer would be great.

 

Thanks,

Lee