Hot answers tagged

98

Good question, I've never considered it before... i've just assumed the platform will play fair and I'm pleased to find it does! System.debug('Before DmlStatements : ' + Limits.getLimitDmlStatements()); System.debug('Before DmlRows : ' + Limits.getDmlRows()); insert new List<Account>(); System.debug('After DmlStatements : ' + Limits....


36

We can use List index Property to get the Id of the failed record .The Index of the List which we are updating and also the result set retrieved has the same index .Using the above property for our advantage we can draft a pseduo code as below List<Database.SaveResult> updateResults = Database.upsert(arudate, false); for(Integer i=0;i<updateResults....


29

The Metadata API does not give access to this information, this is used for org configuration such as custom objects and fields. CurrencyType and DatedConversionRate contain record level information. As per the documentation you linked to, you can use the SOAP API to insert and udpate records in these. All standard and custom objects can also be accessed ...


23

Use a DML database method with a value of false for the optional opt_allOrNone parameter - i.e. Database.SaveResult[] result = Database.Insert(accounts, false); From the docs, Use DML database methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your ...


21

Actual field names are User.ProfileId and UserRoleId. Assign the strings directly: mike.ProfileId = '00Ee0000000LhpB';


19

If you already know the ID of the SObject you want to update then you're right, there's no need to waste a query just to get an SObject instance to work with. Your sample code is very close to working, but you need to remember that the constructors for SObjects are special and accept named arguments, something unique to them in all of apex. Your sample code ...


18

A Savepoint is exactly what you want. This is all apart of Transactions in Salesforce. You will want something like: Savepoint sp = Database.setSavepoint(); try{ // DML statements here insert opps; insert quotes; insert quoteItems; }catch(Exception e){ // An exception was caught. We need to revert back to our Savepoint // This will ...


18

Take a look at the Database.emptyRecycleBin(obj) method or the other variants in the Database class such as Database.emptyRecycleBin(listOfSObjects) For example, to permanently delete a contact with Id of '003i000000O4xYZ' in the recycle bin: Contact c = new Contact(Id = '003i000000O4XyZ'); Database.emptyRecycleBin(c);


18

If you are just looking for a bit of code refactoring of this, creating a list of the fields you want to copy and then looping over the list and making use of methods like SObject.get and SObject.put is a bit cleaner: private static final SObjectField[] FIELDS = new SObjectField[] { Account.FirstName__c, Account.LastName__c, Account....


17

I once started seeing this error and couldn't work out for the life of me why... I eventually realised I was being a bit dim, and following my oft-used practice had a call to Init() inside a constructor, and you can't perform DML operations like this inside the constructor! Update Jan 2014 - Something else to watch out for! Almost a year after writing this ...


17

Once you have the sObjectType you should be able to construct the sObject instance using the sObjectType.newSObject(ID Id) method. You can get the sObjectType from the Id using the Id.getSObjectType() method; Map<Id, String> idsToUpdate = new Map<Id, String>(); // Put the Id's and associated name values in the map List<SObject> ...


17

You should use @future class to avoid this error, as described in the Apex Developer Guide.


16

First, I highly recommend you read Bob's post for yourself. He's a much better writer than I am. Also, Salesforce documents this behavior in Relating Records by Using an External ID and Creating Parent and Child Records in a Single Statement Using Foreign Keys. To relate a record to its parent record with an external ID, the parent object must have a ...


15

Using complex objects as Map keys can have unexpected consequences. In your example, the insert causes the Id of the key Account to be updated so the hashCode and equals methods of the Account produce different results after that. But the Map was setup with the original hashCode and equals results. Effectively you have modified the key and that has broken ...


14

Cause: Transaction Scope I've hit this before, and concluded this is due to how getContent is likely implemented internally. As per the Apex Documentation on transaction handling... all changes are committed to the database only after all operations in the transaction finish executing So the problem is until your database changes are committed, ...


14

These methods give you additional options if you want to something other than the default behaviour the DML Statements give, such as... allowFieldTruncation Specifies the truncation behavior of large strings. assignmentRuleHeader Specifies the assignment rule to be used when creating a case or lead. emailHeader Specifies additional information ...


13

The line provoking the error is actually System.assert(e.getDmlFields(0)[0] == 'Email'); The error is complaining that you're comparing a Schema.SObjectField value with a String, which isn't allowed. It looks like getDmlFields() has changed over the releases. I'll raise a doc bug to get that example code fixed. Changing that line to System.assert(e....


13

Fundamentally DML (Data Manipulation Language) and SOQL (Salesforce Object Query Language) are different in that one creates, updates and deletes data (DML) and the other reads it (SOQL). You will also encounter SOSL (Salesforce Object Search Language), this is another way to read data using advanced search criteria. Literal Usage. Both support the ability ...


13

One time I had to do this. My 7-year old spent about half an hour at my desk clicking the button repeatedly while I went downstairs and made a sandwich. Still easier than writing and promoting a batch for a one time data cleanup.


12

You can use FOR UPDATE to lock a certain record, but it would be locked to the testing transaction, so it might not give you the DML Exception you want. How dependant are you on the content of the DML Exception? If you just want an exception of the correct type use Test.isRunningTest() to deliberately cause the exception. try { // If you can't ...


12

You can submit multiple Records for approval, sample code below. List<Approval.ProcessSubmitRequest> requests = new List<Approval.ProcessSubmitRequest> (); for (Id oppId: opportunities) { Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest(); req1.setComments('Submitting request for ...


12

Transactions have to be fully ACID compliant. The "C" stands for consistency, and this is where transaction control comes in. In order for your Queueable to execute, it has to be guaranteed that the transaction that placed the Queueable into the queue has committed. This means that your Queueable cannot run before the transaction has been fully committed to ...


12

In general, there's no real penalty for using upsert as opposed to insert and update. One notable limitation, however, is that upsert does not support generic SObject[] lists or generic SObject records. This also means you can't take advantage of combining DML calls to reduce governor limit usage. For example, consider this code: Account a = new Account(...


11

For a quick and dirty approach if I have more than 10,000 rows to update through anonymous apex I will sometimes do something like this List<Thing__c> things = [select id from thing__c where status__c = 'Old value' limit 10000]; for (Thing__c thing : things) { // make changes thing.status__c = 'New Value'; } update things; Then run the script ...


11

Run it with the following line commented out and see if it works.. feedList.add( new FeedItem(Body='@'+UserInfo.getName()+'Hello World'+i,ParentId = UserInfo.getUserId())); //Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl()); Test.startTest(); Test.setMock(HttpCalloutMock.class, new MirrorMockTimelinePostImpl()); The Test.startTest ...


10

The authentication mechanism seems to have a replication delay. Changing your user name results in an email being sent to you: Dear Mr. User, Your username has changed. New username: ABC Old username: XYZ The new username may take several minutes to become fully functional. We recommend you log in with the following link for the ...


10

Step 5 refers to a temporary database save; the rows are saved to the database, but the transaction isn't committed. When data is saved to the database, it becomes available to the current transaction. However, a commit is what finalizes the data and releases the lock that allows other transactions to also see that data. In terms of raw SQL commands, each ...


10

Yes, you need to make one field as External id on your parent object. In my case SLASerialNumber__c is external id field. Contact con = new Contact(lastName='bhardwaj'); con.Email = 'naman.bhardwaj@test.com'; Account accRef = new Account(SLASerialNumber__c='12'); con.Account = accRef; Account acc = new Account(Name='namanTestAcc', SLASerialNumber__c='12');...


10

Here ya go. According to Considerations for Creating Custom Controllers and Controller Extensions You can't use data manipulation language (DML) operations in a “getxxx” method in a controller. For example, if your controller had a getName method, you could not use insert or update in the method to create an object FYI: @future methods are ...


9

From the docs: The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing. Apex code runs in system context so even though the user does not have delete permissions since the delete is done via apex it is allowed. You could instead delete the records twice, and the second deletion will cause an error: static ...


Only top voted, non community-wiki answers of a minimum length are eligible