+ Start a Discussion
EtienneCoutantEtienneCoutant 

Hi,

 

Can someone help, I keep getting the error:

System.DmlException: Insert failed. First exception on row 0 with id 00oS0000000AOgYIAW; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]

 

But I am pretty sure that there is no Id specified in my insert call.

Here is my code:

 

 

public PageReference save() { List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>(); List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>(); for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){ for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){ if(revenueSchedule.get('Id') == null) revenueSchedulesToInsert.add(revenueSchedule); else revenueSchedulesToUpdate.add(revenueSchedule); } if(revenueSchedulesToUpdate.size() > 0) update revenueSchedulesToUpdate; if(revenueSchedulesToInsert.size() > 0) insert revenueSchedulesToInsert; } return Page.revenueScheduleView2; }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

You're getting this error becuase you're adding items to list; inserting the list; adding more items to the list; and then trying to insert all the items you've already inserted and the new ones.

 

You shouldn't be performing DML inside a loop, although isn't directly causing your issue. Try this instead:

 

    public PageReference save() {
        List<OpportunityLineItemSchedule> revenueSchedulesToUpdate = new List<OpportunityLineItemSchedule>();
        List<OpportunityLineItemSchedule> revenueSchedulesToInsert = new List<OpportunityLineItemSchedule>();
       
        for(revenueSchedulesDate revenueSchedulesDate:revenueSchedulesDates){
            for(OpportunityLineItemSchedule revenueSchedule:revenueSchedulesDate.getRevenueSchedules()){
                if(revenueSchedule.get('Id') == null)
                    revenueSchedulesToInsert.add(revenueSchedule);
                else
                    revenueSchedulesToUpdate.add(revenueSchedule);
            }
        }
       
        update revenueSchedulesToUpdate;
        insert revenueSchedulesToInsert;       
       
        return Page.revenueScheduleView2;
    }

 

This will help with governor limits(although this still depends on the amoutn of data you work with), and will avoid your other issue.

 

Wes

 

 

uptime_andrewuptime_andrew 

I have an APEX Trigger that runs when a Task is created/updated, so it can update the related Case. 

 

Somehow, the trigger is causing the Case Assignment Rules to re-fire, but I don't know what.  Any thoughts?

 

 

 

trigger caseLastActivityDate on Task (after insert, after update) { Map<String, Task> tMap = new Map<String, Task>(); for (Task t : System.Trigger.new) { String whatId = t.WhatId; System.debug('whatId is ' + whatId); if(whatId <> null && whatId.startsWith('500') == true) { Case c = [select Id from Case where Id = :whatId]; if(c.Id <> null) { c.Last_Activity_Date__c = t.LastModifiedDate; update c; } } } }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
uptime_andrewuptime_andrew

The solution I had for this was two-fold:

 

First, we added a new field, "Case Taken", which is just a boolean.   Once the case is taken by a user (who is not the default assignee), Case Taken is set to true.

 

Second, we updated the assignment rules with an new entry/step where if Case Taken equals True and the owner is not the default assigner, use the "Do Not Reassign Owner" flag.

anil Kumaranil Kumar 
Hi All,

We have few web service call outs from salesforce community portal to external system. External system has been upgraded to TLS 1.2 protocol. Now they wants us to upgrade to LS 1.2 protocol version. Kidly help me how to upgrade TLS 1.2 version in salesforce?

Thanks,
Anil Kumar
Best Answer chosen by anil Kumar
Khan AnasKhan Anas (Salesforce Developers) 
Hi Anil,

Greetings to you!

It is possible to get this upgrade to TLS 1.2 "indirectly" by upgrading your browser to the latest version. You will automatically be using it if you are using updated browsers. Also, you update your JDK to the latest version.

To check if your browser can handle TLS v1.1 and v1.2, select https://www.ssllabs.com/ssltest/viewMyClient.html to open the SSL/TLS Capabilities of Your Browser web page.

Once the page completes the test, scroll down to the Protocol Features section.
  • If Yes is displayed next to TLS 1.1 and/or TLS 1.2, your browser will continue to work as it is currently does with Talent Suite applications.

However, Salesforce is requiring an upgrade to TLS 1.2 by September, 2019, in order to align with industry best practices for security and data integrity. Around this date, Salesforce will begin disabling the TLS 1.1 encryption protocol. 

A new Critical Update Console (CRUC) setting: "Require TLS 1.2 or higher for HTTPS connections" will be made available in the upcoming weeks. You can check the critical updates from Setup -> Search Critical Updates in Quick Find Box -> Select Critical Updates.

Please refer to the below link which might help you further with the above requirement.

https://help.salesforce.com/articleView?id=000221207&type=1

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
TraceyTracey 

I'm trying to copy a new user as contact by using a trigger but I'm getting the following error

 

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): Contact, original object: User

 

trigger Acceleration_User_Copyto_Contact on User (after insert, after update) {
    
   // Map<String,User> newLead = new Map <String, User>();
    
    system.debug('Acceleration_User_Copyto_Contact Trigger....');
 
    for ( User user : System.Trigger.new)
    {
        if  (user.Email.contains('acceleration'))
        {
            system.debug('Acceleration_User_Copyto_Contact Trigger..2.');
            Integer RecordCount = [select count() from Contact c where c.Email = : user.Email];
            
            system.debug('Acceleration_User_Copyto_Contact Trigger..2a .' + RecordCount);
            
            if (RecordCount == 0)
            {
                String AccountId = '';
                for ( Account a : [Select a.Id From Account a where Name = 'Acceleration']) 
                {
                    system.debug('Acceleration_User_Copyto_Contact Trigger..3.');
                     
                    AccountId = a.Id;
                
                    Contact con = New Contact();
                    con.AccountId = AccountId ;
                    con.Email = user.Email;
                    con.Firstname = User.Firstname;
                    con.Lastname = User.Lastname ;
                    con.User__c = User.Id;
                    insert con;
                }          
            }                   
        }
        
     }
    
    
}

 

Best Answer chosen by Admin (Salesforce Developers) 
wesnoltewesnolte

Hey

 

There you cannot perform DML on what salesforce calls setup objects(User in this case) and non-setup object in the same context. There is a workaround that can be found here although I still had some issues. Let me know if the posted solution works for you, if not mail me and I'll send you mine.

 

Cheers,

Wes 

Eric_SantiagoEric_Santiago 
I'm trying to write a simple trigger that renames a record. I keep getting the error "CallLineItemRename: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.CallLineItemRename: line 18, column 9" . What am I missing here?

 

 

 

trigger CallLineItemRename on Call_Line_Item__c (before insert, before update) { // this triger renames the call line item id to be // the specified inventory item name or the product name List<Call_Line_Item__c> callItems = new List<Call_Line_Item__c>(); callItems = Trigger.new; for (Call_Line_Item__c callItem : callItems) { //check if inventory or product was specified if (callItem.Inventory_Item__c <> NULL) { callItem.Name = callItem.Inventory_Item__r.Name; callItem.Name = 'inv item name'; } else if (callItem.Products__c <> NULL) { callItem.Name = callItem.Products__r.Name; } } update callItems; }

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
aalbertaalbert
Remove the update DML statement at the end. By using the "before" trigger to modify the Trigger.new objects, you don't need to explicitly perform an update DML statement. When the trigger ends, it will implicitly update the data as you have modified the values.
vickySFDCvickySFDC 

Hi All,

This two VF tags I am really confusing

Can anyone give examples <apex:actionsupport> and <apex:actionfunction> tags and give some examples?

 

 

Thanks,

 

Vicky

Best Answer chosen by Admin (Salesforce Developers) 
asish1989asish1989

HI

A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An <apex:actionFunction> component must be a child of an<apex:form> component.

 

Used when we need to perform similar action on varioud events. Een though you can use it in place of actionSupport as well where only event is related to only one control.

Example

<!-- Page: -->
	<apex:page controller="exampleCon">
	<apex:form>
		<!-- Define the JavaScript function sayHello-->
		<apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out"
		status="myStatus"/>
	</apex:form>
	
	<apex:outputPanel id="out">
		<apex:outputText value="Hello "/>
		<apex:actionStatus startText="requesting..." id="myStatus">
		<apex:facet name="stop">{!username}</apex:facet>
		</apex:actionStatus>
	</apex:outputPanel>
	
	<!-- Call the sayHello JavaScript function using a script element-->
	<script>window.setTimeout(sayHello,2000)</script>
	<p><apex:outputText value="Clicked? {!state}" id="showstate" /></p>
	<!-- Add the onclick event listener to a panel. When clicked, the panel triggers
	the methodOneInJavascript actionFunction with a param -->
	<apex:outputPanel onclick="methodOneInJavascript('Yes!')" styleClass="btn">
		Click Me
	</apex:outputPanel>
	
	<apex:form>
		<apex:actionFunction action="{!methodOne}" name="methodOneInJavascript"
		rerender="showstate">
			<apex:param name="firstParam" assignTo="{!state}" value="" />
		</apex:actionFunction>
	</apex:form>
</apex:page>

/*** Controller ***/
public class exampleCon {
	String uname;
	public String getUsername() {
		return uname;
	}
	public PageReference sayHello() {
		uname = UserInfo.getName();
		return null;
	}
	public void setState(String n) {
		state = n;
	}
	public String getState() {
		return state;
	}
	public PageReference methodOne() {
		return null;
	}
	private String state = 'no';
}

 

.ActionSupport : A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by theserver when a particular event occurs, such as a button click or mouseover.

 

Used when we want to perform an action on a perticular eventof any control like onchange of any text box or picklist.

 

Example

<apex:page controller="exampleCon">
	<apex:form>
		<apex:outputpanel id="counter">
			<apex:outputText value="Click Me!: {!count}"/>
				<apex:actionSupport event="onclick"
				action="{!incrementCounter}"
			rerender="counter" status="counterStatus"/>
		</apex:outputpanel>
		
		<apex:actionStatus id="counterStatus"
			startText=" (incrementing...)"
			stopText=" (done)"/>
	</apex:form>
</apex:page>


/*** Controller: ***/
public class exampleCon {
	Integer count = 0;
	public PageReference incrementCounter() {
		count++;
		return null;
	}
	public Integer getCount() {
		return count;
	}
}

 If this post answers your questions please mark it as solved and hit kudos button if it helps you

 

Thanks

 

PronowPronow 

Hello there,

 

In my project, on an object I have two fields. One is an auto-update and other is a formula field. Auto-update field contains 'Current Date' value ( 'TODAY()' ). Formula field is number type, calculating difference in days between a custom DATE field and above auto-update DATE field.

 

I am trying to trigger, a workflow rule that will fire when value of formula field would be 30 or 60.

 

Please help me out as the workflow is not getting triggered when the above formula evaluates to true.

 

Thank you in advance.

Best Answer chosen by Admin (Salesforce Developers) 
PronowPronow

Thank you for your response.

 

However, I guess you did not get the actual problem that I faced. The workflow is supposed to fire when the auto-update field i.e. Current date will change. The other field is formula field calculating No. of days between two dates. One is Cutom date field and other is Current date.

 

Even if I try to fire a workflow to update either Current date or No. of days, you need to update that particular record.

 

So, as a conclusion I found a solution to write a Schedular that will fire everyday, and it will calculate no. of days and update it. This will cause all dependent workflows to fire.

 

I implemented this solution in my project, and its working fine and uninterrupted now.

 

Thank you for your knowledge sharing.

Basil DobekBasil Dobek 
Hi, I'm trying to create a new empty project using the Salesforce CLI and I receive the message "ERROR running force:project:create  Cannot read property 'create' of undefined".    Does anyone know what might be causing this or how to further troubleshoot it? 

The command I'm entering in the terminal is "sfdx force:project:create --projectname VSCodeQuickStart".   I've tried "sfdx force:project:create --projectname VSCodeQuickStart --manifest" as well.


Thank you


 
Best Answer chosen by Basil Dobek
Khan AnasKhan Anas (Salesforce Developers) 
Hi Basil,

Greetings to you!

Please make sure you are using the latest version of salesforcedx. Try to update the CLI
sfdx update

If the problem still persists, uninstall the salesforcedx and reinstall it.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
RarLopzRarLopz 
Can someone please assist, how do i get around this exception of 'Too many query Rows 5001'

 
list<Id> accId = new list<Id>();

list<Contact> conDSA = [Select Id, Name, DSA__c, AccountID from Contact 
                        Where DSA__c = true AND AccountID!=null ];

system.debug('Number of Contacts that are DSA ' +conDSA.size());
for (Contact c: conDSA){
system.debug('>>> ' +c.Name + c.AccountId);
    accId.add(c.AccountId);

}

list<AccountContactRelation> acr = [SELECT Id, isDSA__c,AccountId, ContactId 
                                    FROM AccountContactRelation 
                                    Where AccountId IN :accId ];

system.debug('Number of records in ACR are: ' +acr.size());

for (AccountContactRelation a: acr){
    	a.isDSA__c = true;
}
update acr;

 
Best Answer chosen by RarLopz
Raj VakatiRaj Vakati
Looks like you are calling this code from the developer console so you are getting the  all the record so can you try like this

 
list<Id> accId = new list<Id>();

list<Contact> conDSA = [Select Id, Name, DSA__c, AccountID from Contact 
                        Where DSA__c = true AND AccountID!=null Limit 500];

system.debug('Number of Contacts that are DSA ' +conDSA.size());
for (Contact c: conDSA){
system.debug('>>> ' +c.Name + c.AccountId);
    accId.add(c.AccountId);

}

list<AccountContactRelation> acr = [SELECT Id, isDSA__c,AccountId, ContactId 
                                    FROM AccountContactRelation 
                                    Where AccountId IN :accId Limit 9999];

system.debug('Number of records in ACR are: ' +acr.size());

for (AccountContactRelation a: acr){
    	a.isDSA__c = true;
}
update acr;

https://help.salesforce.com/articleView?id=000181404&language=en_US&type=1
RupBRupB 

Hi,

 

- Sorry to bother, but I found no answer to this wuestion either on the web, or in the dev forum, or in the Apex documentation - 

 

I have a trigger, which detects error conditions and feeds errors to the class or field.

This gives a nice result interactively, in the GUI.

But how do I write test code to catch these errors ?  Is there a System.AssertException(), or the equivalent ? 

 

trigger createOrder on Asset (after insert, after update) {[...] if (price.get(a.Product2Id) == NULL) { System.debug(' error : no active price'); a.Product2Id.addError('no active price on the Product'); }[...]}

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdccoder1sfdccoder1

Hi RupB,

 

I worked out a solution for a similar case I had where addError() was used for a record and not for a field.

I  believe though it should work for your case too.

 

The idea is to:

 

a. Write code in the test class that will cause the trigger to 'addError()'.

b. Surround the above test class code with try - catch.

cAssert that an exception is thrown and that the exception message is the same one you created with 'addError()'.

 

Here's an example (partly pseudo) code from both trigger and test class:

 

Trigger: 

 

if(myRecord.MyField == some value)

myRecord.addError('My Error Message');

 

 

Test Class: 

 

try

{

MyRecord.MyField = a value that will cause an error

update MyRocord;

throw new MyException('An exception should have been thrown by the trigger but was not.'); // 1. If we get to this line it means an error was not added and the test class should throw an exception here. 2MyException class extends Exception.

}

catch(Exception e)

{

Boolean expectedExceptionThrown =  e.getMessage().contains('My Error Message')) ? true : false;

System.AssertEquals(expectedExceptionThrown, true);

 

 

Let me know if this did the work

 

 

Message Edited by sfdccoder1 on 09-01-2009 01:32 AM