0

This question already has an answer here:

Heres the error that I'm getting:

Execution of AfterUpdate caused by: System.QueryException: List has no rows for assignment to SObject ()

I believe the issue is with the following lines, which aims to retain the current account owner when a lead is converted automatically by the trigger:

Account a = [SELECT OwnerId FROM Account WHERE Id=:accountId LIMIT 1]; lc.setOwnerId(a.OwnerId);

trigger autoconversion on Lead (after update)
{
  Lead ld=Trigger.new[0]; 
  if( ld.Ready_to_Convert__c == TRUE && ld.IsConverted == FALSE) {
      Database.LeadConvert lc = new database.LeadConvert();
      lc.setLeadId(ld.id);
      lc.setAccountId(ld.Linked_AccountId__c);
      lc.setDoNotCreateOpportunity(TRUE);
      String accountId = ld.Linked_AccountId__c; 
      //Account a = [SELECT OwnerId FROM Account WHERE Id=:accountId LIMIT 1];

      List<Account> accs = [SELECT OwnerId FROM Account WHERE Id=:accountId LIMIT 1];
      Account a = null;

      if (!accs.isEmpty()) {
          a = accs[0];
          lc.setOwnerId(a.OwnerId);
      }else {
          a = null;
          }

      LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
      lc.setConvertedStatus(convertStatus.MasterLabel);
      Database.LeadConvertResult lcr = Database.convertLead(lc);
  }
}

marked as duplicate by Lukas Lunow, Pranay Jaiswal, glls, Sebastian Kessel, battery.cord May 17 at 13:23

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

A query of the form:

SObjectOfSomeForm__c thing = [SELECT Id, ... FROM SObjectOfSomeForm__c WHERE ... LIMIT 1];

will fail when the SELECT doesn't find any records. To address this scenario in your code you have to do:

List<SObjectOfSomeForm__c> things = [SELECT Id, ... FROM SObjectOfSomeForm__c WHERE ... LIMIT 1];
SObjectOfSomeForm__c thing = null;

if (!things.isEmpty()) {
    thing = things[0];
}
...

It would have been nice if Apex just set your variable to null if there were not records found, but it does not.

  • Thank you for your quick reply, would you be able to clarify further as I am very new to development & you're very experienced & knowledgable.. – Phillip Wood May 16 at 10:42
  • What additional clarity do you require? The problem in your code is the LeadStatus convertStatus = [SELECT ... LIMIT 1]; call I believe. Make this a list. I would also recommend that you add various checks such as making sure your "accountId" variable is not null before doing the later query using the value. – Phil W May 16 at 11:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.