trigger trig1 on Account (before insert)
{
list<contact>c=new list<contact>();
for(account a:trigger.new)
{
contact ct=new contact();
ct.LastName=a.Name;
c.add(ct);
}
insert c;
}
| account name dup is created |
integer count=0;
list<account>acc=[select id,name from account where createddate=today];
for(account a:trigger.new)
{
count=acc.size();
if(count>1)
{
a.adderror('limit');
}
}
}
| create new record |
| create another record error message will come because limit is 1 only one record can be created. |
3.write trigger for contact when ever we create or update contact record number of contacts created update shoulb be vissible in account field or if you delete olso number should be decreased?
trigger trigcountdel on Contact (after INSERT, after UPDATE, after DELETE)
{
list <string> accountIds = new list <string>();
List <Account> lstAccountsToUpdate = new List <Account>();
if(Trigger.isInsert){
for(Contact con:trigger.new){
accountIds.add(con.accountID);
}
}
if(Trigger.isDelete){
for(Contact con:trigger.old){
accountIds.add(con.accountID);
}
}
if(Trigger.isupdate){
for(Contact con:trigger.new){
accountIds.add(con.accountID);
}
}
for(Account acc:[SELECT Id,Name,countcontact__c,(Select Id from Contacts) from Account where Id IN: accountIds])
{
Account accObj = new Account ();
accObj.Id = acc.Id;
accObj.countcontact__c = acc.Contacts.size();
lstAccountsToUpdate.add(accObj);
}
UPDATE lstAccountsToUpdate;
}
| create a new contact |
| create new contact and account lookup select any record from account i selected count |
It's very nice...Provide more examples
ReplyDeletethankyou for your comment.....sure i will provide more examples that will help you for your interview
Delete