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
aaryansriaaryansri 

Trigger based on Count and Price Condition

 Define a Validation on Book Sobject that will not allow to create more than 10            books with cost greater that 500


For this i tried out below trigger code getting error
trigger count on book__c (before insert) {
integer d=[select count() from book__c];
 for(book__c c : trigger.new){

system.debug('***********************'+d);
if(c.price__c >=500)
{system.debug('***********************'+c.price__c);
 insert c;   
}

else
{
 c.adderror('not allowed');
}
}
}

pconpcon
What kind of error are you getting?
aaryansriaaryansri
Hi

    I am getting below error when giving value more that 500 and  if below 500 it else part is executing.

 Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger count caused an unexpected exception, contact your administrator: count: execution of BeforeInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.count: line 8, column 1.

                                             Please check and correct the error.
Anoop yadavAnoop yadav
Hi Ashokk,

You can not use DML here. try the below code.

trigger count on book__c (before insert) {
	integer d=[select count() from book__c];
	for(book__c c : trigger.new){
		system.debug('***********************'+d);
		if(c.price__c <500) {
			c.adderror('not allowed');
		}
	}
}

for more information on this .
check the below link.

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_context_variables_considerations.htm



pconpcon
As Anoop said, you don't need to do the insert since this is in a before trigger.