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
lohith mlohith m 

Trigger

how to write a trigger on a object that user can create only one record , but if any other person trying to create another record it should throw error.
Rajiv Bhatt 16Rajiv Bhatt 16
In the trigger just execute soql on that object and check for total number of records, if the count is not zero then throw an error 
ManojjenaManojjena
Hi Lohith ,

Please use below code .
trigger OnlyOne act (before insert) {
   Integer count =[SELECT count() FROM Contact];
   if(count ==0){
   //ADD LOGIC BELOW 
}

 
SantoshChitalkarSantoshChitalkar
Hi Lohith,

Refer the following code - 
 
trigger OnlyOneRecord on Account(before insert){
      List<Account> lstAccount = [Select Id from Account];
      Boolean createRecord = false;
       if(lstAccount.size() > 1)
          createRecord = true;
       for(Account a : trigger.new){
           if(createRecord == true)
            a.addError('You can create only one record for Account );
       } 
}

Mark this as solve and choose the best answer if this answers your question.

Regards,
Santosh Chitalkar
lohith mlohith m
Thank u SantoshChitalkar