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
VisithraVisithra 

Am in DML Topic..i need to insert a record in employee__c object, if name is new it shoud insert if not it should display message as aleready exist

my code is
public class Emp {
    public boolean ifExists=false;
    
    
    public void insertEmp(string empName)
    {
        List<Employee__c> empl=[SELECT 
                                Id, Name 
                                FROM Employee__c];
        for(Employee__c E: empl){
                if(empl.Name!=empName){
                    insert empl;
                }
        }if(ifExists==true){
            system.debug('Record already exists with the same employee name!..Create Another Name.!');
        }
            }
        }


here it is allowing me to insert everytime with same name..
 
Best Answer chosen by Visithra
SubratSubrat (Salesforce Developers) 
Hello Visithra ,

There are some issues with your code ,
Please try with below :
 
public class Emp {
    public void insertEmp(String empName) {
        List<Employee_c> existingEmployees = [SELECT Id, Name FROM Employee_c WHERE Name = :empName];
        if (existingEmployees.size() > 0) {
            System.debug('Record already exists with the same employee name! Create another name.');
        } else {
            Employee_c emp = new Employee_c();
            emp.Name = empName;
            insert emp;
        }
    }
}

If it helps please mark this as Best answer.
Thank you.

All Answers

SubratSubrat (Salesforce Developers) 
Hello Visithra ,

There are some issues with your code ,
Please try with below :
 
public class Emp {
    public void insertEmp(String empName) {
        List<Employee_c> existingEmployees = [SELECT Id, Name FROM Employee_c WHERE Name = :empName];
        if (existingEmployees.size() > 0) {
            System.debug('Record already exists with the same employee name! Create another name.');
        } else {
            Employee_c emp = new Employee_c();
            emp.Name = empName;
            insert emp;
        }
    }
}

If it helps please mark this as Best answer.
Thank you.
This was selected as the best answer
VisithraVisithra
thanks this works..but when declaring fields in class level varible., how can be done with this code?