You need to sign in to do that
Don't have an account?

Apex trigger for newbie - restricting ability to create entries via related list.
Hopefully a relatively simple trigger.
I have a related list on a custom object. There is a certain Record Type that I want the user to only be able to create ONE entry/relationship with. If they try to create two entries, I want to pop an error with some information for the user.
Hi,
Please try below :-
Trigger createnewRecord on Child__c(before insert){
List<Id> parentIds = new List<Id>();
for(Child__c dc:trigger.new){
if(dc.recordTypeId == <recordtypeid>) { // put the recordTypeId for which you want to restrict
parentIds.add(dc.Parent__c); //Assuming the relationship field on child object is Parent__c
}
}
List<Parent__c> parentList = [select id,(select id from child__r) from Parent__c where id in:parentIds];
for(Child__c dc:trigger.new){
if(parentList[0].child__r>=1){
c.addError('You cant create more children with this recordtype');
}
}
}
trigger preventInsert on sObject(before insert)
{
Boolean flag;
Id rtId = [Select Id, Name from RecordType where name = 'recordtypename' limit 1].Id;
for(sObject temp : Trigger.new)
{
Id recordRtId = [Select RecordTypeId from parentObject WHERE ID=:temp.parentObjectLookup].Id;
List<childObject> pOb=[SELECT ID FROM childObject WHERE parentObjectLookup=:temp.parentObjectLookup];
if(recordRtId==rtId && pOb.size()==1)
temp.addError('error message');
}
}
Thanks guys, I may have to return to this later as I may be revising the entire set of objects.