function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Akshay SethiaAkshay Sethia 

Apex Class Data insert

public with sharing class dataFetch {
  @AuraEnabled(cacheable=true)
  public static PayUser__c getUser() {
    PayUser__c user = [
      SELECT Id, Name, Email__c, Contact_Number__c
      FROM PayUser__c
      WHERE Email__c = :userinfo.getUserEmail()
      LIMIT 1
    ];
    if (user == null) {
      try {
        PayUser__c newUser = new PayUser__c(
          Name = userinfo.getName(),
          Email__c = userinfo.getUserEmail()
        );
        insert newUser;
        return newUser;
      } catch (Exception e) {
        System.debug('An unexpected error has occurred: ' + e.getMessage());
        return null;
      }
    } else {
      return user;
    }
  }
}



This is my apex class, in this i want to insert a PayUser record if one is not present. can anyone help me
vishal-negandhivishal-negandhi

Hi Akshay, 

When you're querying for the PayUser, if there are no users available, you'll be getting an exception since the query returns no rows to assign to your object. 

We need to modify your code slightly and then it should work, hopefully ;)
 

public with sharing class dataFetch {
  @AuraEnabled(cacheable=true)
  public static PayUser__c getUser() {
    List<PayUser__c> user = [
      SELECT Id, Name, Email__c, Contact_Number__c
      FROM PayUser__c
      WHERE Email__c = :userinfo.getUserEmail()
      LIMIT 1
    ];
    if (user.isEmpty()) {
      try {
        PayUser__c newUser = new PayUser__c(
          Name = userinfo.getName(),
          Email__c = userinfo.getUserEmail()
        );
        insert newUser;
        return newUser;
      } catch (Exception e) {
        System.debug('An unexpected error has occurred: ' + e.getMessage());
        return null;
      }
    } else {
      return user[0];
    }
  }
}

We changed your PayUser__c object to a list, and then we check if the list is empty in which case you'll create a new user. 

 

Hope this helps.

 

Best,

Vishal