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
Sales Force FRMSales Force FRM 

how to invoke my own class from trigger

    Hi folks,
                   how to invoke my own class from trigger for ex:
                   my class is follows :

global class InsertAccount{


webservice static String createAccount(String accName){

String createdAccounts='';
String message='';
String firstName='rajeshwar';
String secondName='Suhel Ahmed';
Integer count=0;
try {
count=[select count() from account where name like : (firstName)];
if(count>0){
message='The Account \' '+firstName+'\' already in use!';
}else{
Account first = new Account();
first.name=firstName;
first.type='prospect';
Account[] accs = new Account[]{first};
// Attempt to insert it...
insert accs;
message='The Account \' '+firstName+'\' created Successfully!';
}



} catch (ListException e) {
// But will get here
}
return message;
}

}
now i want to invoke this class from trigger by passing account name as parameter in
createAccount(String accName) method, 

How can i achieve this , please let me know!

Regards,
Raeshwar.
werewolfwerewolf
That's pretty easy.  Your method is static anyway, so just make a trigger of some sort from which you can get to Account, iterate through each of the Trigger.new items (which will all be accounts), and pass its name to InsertAccount.createAccount.
 
That said, you realize that if you make an trigger on Account before insert, you'll end up creating the account twice and probably get yourself into an infinite loop, right?  You probably don't actually want to call this code here with a trigger.  Really, if you're just trying to prevent duplicate accounts, don't actually create the account in your code here.  Just look up the name and throw a ValidationException if an account by that name already exists.  That will tell the trigger to tell the page that this account cannot be created.
 
Incidentally, there's an easier, non-Apex way to do this.  See the thread here: