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
dany__dany__ 

when i am trying to execute this trigger ............ System.SObjectException: DML statment cannot operate on trigger.new or trigger.old

trigger custom1 on student__c (before insert)
{
list <student__c>st1= new list <student__c>();

for(student__c st:trigger.new)
{
   if(st.sport__r.name=='rugby')
    {
      st.stdno__c=12345;
   
}
insert st;
}
}
Best Answer chosen by dany__
Ankit AroraAnkit Arora
I think there is no other problem, and your this condition

if(st.sport__r.name=='rugby')

is not getting true. Use debugs and check what you are getting in "st.sport__r.name". It should exactly matches 'rugby' and this check is case sensitive.

All Answers

Ankit AroraAnkit Arora
You don't need to use insert in before insert trigger, try with this :

trigger custom1 on student__c (before insert)
{
list <student__c>st1= new list <student__c>();

for(student__c st:trigger.new)
{
   if(st.sport__r.name=='rugby')
    {
      st.stdno__c=12345;
   
}
}
}


dany__dany__
thnx for  ur fast reply ........... but it's not inserting 
praveen murugesanpraveen murugesan
Pradeep,

What is error you are geeting 

trigger custom1 on student__c (before insert)
{
list <student__c>st1= new list <student__c>();

for(student__c st:trigger.new)
{
   if(st.sport__r.name=='rugby')
    {
      st.stdno__c=12345;
   
}
}
}

in this??

Thanks.


dany__dany__
i am not geeting any error .....................but field   'std no is not getting  inserted' 

praveen murugesanpraveen murugesan
Pradeep,

Check if there is any validation rule,

Else deactivate this trigger and check.

Thanks
dany__dany__
no i dont have any validation rules for this object 
praveen murugesanpraveen murugesan
What is happening if trigger is inactive??
Ankit AroraAnkit Arora
I think there is no other problem, and your this condition

if(st.sport__r.name=='rugby')

is not getting true. Use debugs and check what you are getting in "st.sport__r.name". It should exactly matches 'rugby' and this check is case sensitive.
This was selected as the best answer
KaranrajKaranraj
Hi,

The problem is since we are using relationship field in the condition, which always null when we use the trigger.New in the before trigger, eventhough your are have proper value in the object. Hope below will resolve your issue

trigger custom1 on student__c (before insert)
{
	for(student__c st: [Select Id,Name,sport__r.Name from Student__c where Id IN: trigger.newMap.keyset()])
	{
   		if(st.sport__r.Name =='rugby')
   		{
    		st.stdno__c=12345;
   		}
	}
}