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
surendra kumar 7surendra kumar 7 

trigger duplicatename

im write the trigger duplicate name on student object its show an error

Error :required (...)+ loop did not match anything at input 'trigger'
trigger duplicatename on student__c (before insert)
{
    list<student__c> stlist=trigger.new;
    list<student__c> stnewlist=new list<student__c>();
    for(student__c st:stlist)
    {
        stnewlist=[select id,name from student__c where name=st.name];
        if(stnewlist.size()>0)
        {
            st.adderror('you cant insert a record with duplicate name');
        }
    }
        }  
Sumitkumar_ShingaviSumitkumar_Shingavi
Your trigger have several issues like it's not bulkified and syntactic problems.

I wrote below code for you:
trigger duplicatename on student__c (before insert) {
	//Collect all names for current context	
	Set<String>	sNames = new Set<String>();	
	for(Student__c stud : Trigger.new) {
		sNames.add(stud.Name);
	}
	
    //Create Map of existing students where Name as Key and Value as Student Record
	Map<String, Student__c> mStudents = new Map<String, Student__c>();
	for(Student__c stud : List<Student__c> lStudents = [SELECT id, Name FROM Student__c WHERE Name in : sNames]) {
		mStudents.put(stud.Name, stud);
	}
	
    //Check if Map contains the student in current context students. If yes, that means you have a duplicate
	for(Student__c stud : Trigger.new) {        
        if(mStudents != Null && mStudents.containsKey(stud.Name)) {
            st.adderror('you cant insert a record with duplicate name');
        }
    }
}

Hope this helps buddy!

PS: if this answers your question then hit Like and mark it as solution!