+ Start a Discussion
Tanu SuriTanu Suri 
I need to extract records from an external application database table and Create a new table (custom object named CustomObj) in Salesforce to receive the data upload (upsert this based on the id using Data Loader).

I need to create an Apex Batch job so that it can be scheduled and from the uploaded data, need to create SOQL statement to fetch some fields from CustomObj and Upsert those fields to Product2 object in Salesforce.

My issue is when I run the Apex Batch job second time it inserts the same set of records again in Product2 object when it should have done the update operation. It causes duplicate records in Product2 object. Below is my code to have a look. Please help me.

global class ProductUpsertBatch implements Database.Batchable<sobject> {
   // Start Method
   global Database.QueryLocator start(Database.BatchableContext bc) {
            return Database.getQueryLocator('Select id, ExternalAppUniqueId__c, Name, Description__c, Category__c, uom__c, Cost_Price__c From CustomObj__c');
       }
       //execute method
       global void execute(Database.BatchableContext bc, List<sObject> scope) {

           list<Product2> newObjects = new list<Product2>();

           for(Sobject s : scope){
               CustomObj__c obj = (CustomObj__c) s;
               newObjects.add(new Product2(
                   ExternalId = obj.id,
                   ProductCode = obj.Name,
                   Name = obj.Formula_Description__c,
                   QuantityUnitOfMeasure = obj.uom__c,
                   Description = obj.Category__c,
                   Cost_Price__c = obj.cost_price__c
               ));
           }
           upsert newObjects;
               }
       //finish method
       global void finish(Database.BatchableContext bc) {
          system.debug('ProductUpsertBatch is finished processing');
       }
}
Best Answer chosen by Tanu Suri
Waqar Hussain SFWaqar Hussain SF
Hi Tanu,

There is no standard field with name ExternalId on Product2 standard object. If you are using custom field, you will have to append __c such as ExternalId__c and make sure that you have checked External Id checkbox in the custom field defination. 
Kira KeoganKira Keogan 
I am stuck on a challenge about creating an account with a related contact. Do I have to make the contact for another account first and then relate it to a different account? I am lost
Best Answer chosen by Kira Keogan
Thomas MonsonThomas Monson
Start by creating the account,  I think its called Garcia Inc.  Then create a new contact and enter the name given in the challenge and when you get to the account field on the contact you are creating use the lookup button to find Garcia Inc.  

Please make sure to mark this as the correct answer if it solves your issue
Best Answer chosen by pooja h 1
Raj VRaj V
Change command button as shown below 
 
<apex:commandButton action="{!save}" value="Save"/>

 
pooja h 1pooja h 1 

Hi,
1) I'm learning salesforce through trialhead. Currently working in Visual force module. When I run the below Program in visualforce page I recieve a blank page as an outputand unable to view the account content in the page.
INPUT:
<apex:page standardController="Account" >
<apex:outputField value="{! Account.Name }"/>
<apex:outputField value="{! Account.Phone }"/>
<apex:outputField value="{! Account.Industry }"/> <apex:outputField value="{! Account.AnnualRevenue }"/>
</apex:page>
OUTPUT:
User-added image

2)How to change javascript console in chrome and why it is needed?
Please someone help me for better understanding

Thanks in advance!
Best Answer chosen by pooja h 1
Waqar Hussain SFWaqar Hussain SF
Hi Pooja,

Since you are using standard controller of account. You will have to put Id of account in the URL parameter. 
such as

.../apex/AccountDetail?Id=XXXX
where XXXX is account Id

I did not get your second question. If you want to debug the apex code. You can activate debug logs by 
Setup > Debug Log

Thanks
 
bhanu prakash 153bhanu prakash 153 
Hi team,

I have designed a trigger to update date__c field of contact on account object Date__c . Now i want to modify code with help of trigger handler class . How can I acheive it ?
trigger LatestDateContact on Contact (after insert,after update,after delete) {    
    List<Account> updAcc = new List<Account>();  
    Map<id,account> mapacc = new Map<id,account>( [select id,name,Date__c,(select id,Date__c from contacts) from account]);
    if(Trigger.isDelete) {
        List<Contact> oldContatcs = Trigger.Old;
        for(Contact con: oldContatcs) {
            Id accID = con.AccountID;
            date latestdate = Date.newInstance(2008, 1, 1);
            Account acc = mapacc.get(accID);
            for(Contact c: acc.Contacts) {
                if(latestdate < c.Date__c ) {
                    latestdate = c.Date__c;
                }
            }
            acc.Date__c = latestdate;
            updAcc.add(acc);
        }
        update updAcc;
    }
    if(Trigger.isInsert || Trigger.isUpdate) {
        List<Contact> newContacts = Trigger.New;
        for(Contact con: newContacts) {
            Id accID = con.AccountID;
            date latestdate = con.Date__c;
            if(latestdate == null) {
                latestdate = Date.newInstance(2008, 1, 1);
            }
            Account acc = mapacc.get(accID);
            for(Contact c: acc.Contacts) {
                if(latestdate < c.Date__c ) {
                    latestdate = c.Date__c;
                }
            }
            acc.Date__c = latestdate;
            updAcc.add(acc);
        }    
        update updAcc;
    }    
}


Thanks for advance 
 
Best Answer chosen by bhanu prakash 153
KapilCKapilC
Hi Bhanu,

Please find the updated code below.
trigger LatestDateContact on Contact (after insert,after update,after delete) {
 if(Trigger.isAfter){
		if(Trigger.isUpdate) {   
	         ContactTriggerHandler.onAfterUpdate(trigger.new,trigger.oldMap);      
	    }else if(Trigger.isInsert) {
	         ContactTriggerHandler.onAfterInsert(Trigger.new);
	    }else if(Trigger.isDelete) {
	         ContactTriggerHandler.onAfterDelete(trigger.OldMap);
	    }
	}
}
Class code is below.
public without sharing class ContactTriggerHandler {
		public static void onAfterUpdate(list<Contact> newList,Map<Id,Contact> oldMap){
			list<account> filerAccountList = filerAccounts(newList);
			if(!filerAccountList.isEmpty()){
				update filerAccountList;
			}
		}
		
		public static void onAfterInsert(list<Contact> newList){
			list<account> filerAccountList = filerAccounts(newList);
			if(!filerAccountList.isEmpty()){
				update filerAccountList;
			}
		}
	
		public static void onAfterDelete(Map<Id,Contact> oldMap){
			list<account> filerAccountList = filerAccounts(oldMap.values());
			if(!filerAccountList.isEmpty()){
				update filerAccountList;
			}
		}
		
		private static list<account> filerAccounts(list<contact> contactList){
		 set<id> accountIdSet = new set<id>();
			for(contact con : newList){
				if(con.accountId != null){
					accountIdSet,add(con.accountId);
				}
			}
			list<account> accountToUpdateList = new list<account>();
			date latestdate = Date.newInstance(2008, 1, 1);
			for(account acc : [select Id, Date__c,(select Id,Date__c from contacts order by Date__c desc limit 1) from account]){
					for(contact con : acc.contacts){
						if(latestdate < con.Date__c){
							acc.Date__c = con.Date__c;
							accountToUpdateList.add(acc);
						}
					}
			}
			return accountToUpdateList;
		}
}



If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Regards,
Kapil
(forcecube@gmail.com)
Ciprian Stoica 12Ciprian Stoica 12 
Hi,

I'm creating a REST WebService that allows placing an order for a product.
Basically, I'm receiving an HTTP Post with a list of products and quantity.

When I receive the message my webservice creates a new order, but I can't seem to place the order.id as a parameter in my list json for each of the products.

My webservice is this:
 
global static list<Coffee_Order_Product__c> echoMyType(list<Coffee_Order_Product__c> ic) {
    Coffee_Order__c newOrder = new Coffee_Order__c();
        insert newOrder;
    for(Coffee_Order_Product__c:ic) {
        ic.add(newOrder.Id);
    }
    insert ic;    
    return ic;
    }
	 
}

my JSON should be:
{
    "ic" : [
                   { "Order_Qty__c" : "7", "Cofee__c" : "a010O000029R3b6QAC","Name" : "prod1"},
                   { "Order_Qty__c" : "4", "Cofee__c" : "a010O000029R3baQAC","Name" : "prod2"},
                   { "Order_Qty__c" : "1", "Cofee__c" : "a010O000029R3b6QAC","Name" : "prod3"}
             ]
}
I get an unexpected token ':' at line : for(Coffee_Order_Product__c:ic)

Any help please?

 
Best Answer chosen by Ciprian Stoica 12
Waqar Hussain SFWaqar Hussain SF
You are adding Coffee_Order__c  in list of Coffee_Order_Product__c. which is wrong

See below code snippet
global static list<Coffee_Order_Product__c> echoMyType(list<Coffee_Order_Product__c> ic) {
    Coffee_Order__c newOrder = new Coffee_Order__c();
        insert newOrder;
    for(Coffee_Order_Product__c c:ic) {
        //ic.add(newOrder.Id);
		//here you can assign values to Coffee_Order_Product__c
		c.YOUR_CUSTOM_FIELD__C = newOrder.Id;
    }
    insert ic;    
    return ic;
    }
	 
}

 
Bas BrusselBas Brussel 
Hi Members I have a after update trigger that calls a class method.
But the update fails with the error: Apex trigger caused an unexpected exception:ANNOT_INSERT_UPDATE_ACTIVATE_ENTITY.

Here is is the code, the error is ocated at line code: "Update gloOppty;"
trigger TotalAmountGlobalOpportunity on Opportunity (after insert, after update, after undelete) {
Opportunity[] Opptys = Trigger.new;
    
   id GlobalOp = 'xxxx00000H1XuHQAV';
   Opportunity gloOppty = [select id, amount, StageName from opportunity where id =:GlobalOp];
   gloOppty.StageName = 'Closed Won'; 
    //System.debug(gloOppty);
   Update gloOppty;  
   
}

Can anyone suggest ?

Br,
Bas
Best Answer chosen by Bas Brussel
Waqar Hussain SFWaqar Hussain SF
Hi Bas,

The issue with your trigger is that, you trigger is recursive. When you will update an opportunity, trigger will run and will update another opportunity. When another opportunity will be update the trigger will run again and then recusion will start. The trigger will keep running.

 
bhanu prakash 153bhanu prakash 153 
Hi Team,

I have amount__c in both contact and account . if account has many contacts  and i need to update highest amount of contacts and update that into account amount field ?

Ex : ABC account   Amount__c  =

       Contact1 :  T -- Amount__c = 500$
       Contact2 :  A -- Amount__c = 700$
       Contact3 :  B -- Amount__c =300$

now account amount__c need to update with 700$ . how can i acheive it using trigger
Best Answer chosen by bhanu prakash 153
GauravendraGauravendra
Hi Bhanu,

Yes, you are right. I didn't cover the delete scenario. Try this new code.
trigger HighestAmountContact on Contact (after insert,after update, after delete) {
    List<Account> updAcc = new List<Account>();
    Map<id,account> mapacc = new Map<id,account>( [select id,name,Amount__c,(select id,Amount__c from contacts) from account]);
    if(Trigger.isDelete) {
        List<Contact> oldContatcs = Trigger.Old;
        for(Contact con: oldContatcs) {
        	Id accID = con.AccountID;
            Decimal highAmnt = 0;
            Account acc = mapacc.get(accID);
            for(Contact c: acc.Contacts) {
                if(highAmnt < c.Amount__c ) {
                    highAmnt = c.Amount__c;
                }
            }
            acc.Amount__c = highAmnt;
            updAcc.add(acc);
        }
        update updAcc;
    }
    if(Trigger.isInsert || Trigger.isUpdate) {
        List<Contact> newContacts = Trigger.New;
        for(Contact con: newContacts) {
            Id accID = con.AccountID;
            Decimal highAmnt = con.Amount__c;
            if(highAmnt == null) {
                highAmnt = 0;
            }
            Account acc = mapacc.get(accID);
            for(Contact c: acc.Contacts) {
                if(highAmnt < c.Amount__c ) {
                    highAmnt = c.Amount__c;
                }
            }
            acc.Amount__c = highAmnt;
            updAcc.add(acc);
        }    
        update updAcc;
    }
    
}
Let me know, if this solves your problem.
Hope this helps.
maninder singh 50maninder singh 50 
When attempting to create my Apex trigger for this Trailhead development exercise, I receive about 20 errors similar to Unexpected token '<'. , Unexpected token 'and'. etc.

trigger AccountAddressTrigger on Account (before insert, before update) {
  List<Account> acc = [Select id from account where Id in :trigger.new and BillingPostalCode!= null and Match_Billing_Address__c == true];
       for(Account a: acc)
    {
      a.ShippingPostalCode = a.BillingPostalCode;        
    }  
}

If i use below query there are no errors.
List<Account> acc = [Select id, Match_Billing_Address__c from account where Id in :trigger.new and BillingPostalCode!= null];

So, there is something wrong with the other Match_Billing_Address__c field and I validated that the API name is correct. I know there are other solutions available for same challenge but please help in debugging this.
 
Best Answer chosen by maninder singh 50
Jainam ContractorJainam Contractor
Hi Maninder,

It seems that the Field Match_Billing_Address__c is of type Checkbox. Is my Understanding correct..???

Also you need not put '==' in the SOQL query. It should be single '=' sign

So, if Match_Billing_Address__c is of type Checkbox, Update your SOQL as below:
 
List<Account> acc = [Select id from account where Id in :trigger.new and BillingPostalCode!= null and Match_Billing_Address__c = true];

Let me know if it helps. Mark this as the solution if it solved your purpose.

Let me know if you need any more assistance.

Thanks & Regards,
Jainam Contractor,
Salesforce Consultant,
Varasi LLC
www.varasi.com
Rakshana ShreeRakshana Shree 
Hi All,
I need help on the chatter group issue.
I have created a chatter group in partner portal but I can't see the group in my internal org even every post is not feeded in internal chatter feed. Should I do anything for getting this?
I hope someone can assist me to do this. 



Thanks,
Rakshana
Best Answer chosen by Rakshana Shree
NagendraNagendra (Salesforce Developers) 
Hi Shree,

Sorry for this issue you are encountering.

May I suggest you please check with below link from the community forums which might help you with the above issue. Please let us know if this helps.

Thanks,
Nagendra