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
Hannes RettigHannes Rettig 

'Variable does not exist' for a custom object

Hallo,
I'm absolutely new with APEX Code, so this is in my opinion just a simple question:
I want to validate a date field over a few objects. So I wrote a trigger and wanted to test
it, here's the code:
 
trigger TimeValidation on Time__c (before insert) {
    
Set<String> TNames = new Set<String>();

for (Time__c tt : Trigger.New){

Time__c.add(tt.Date__c);
}
    
List<Time__c> lstTT = [select id from Time__c where Date__c = tt.Date__c];
    
if (lstTT.size() > 0){
Trigger.New[0].Name.addError('Duplicate Error!!');
}
}
What I want to do is: When sombedy makes a new entry on Time__c I want to validate if there is still an entry with the same date es currently entered. When there's an entry found, I want have an error and reject the entry.

So as it is one of my first triggers I have the questions:

- In the line 'for (Time__c tt : Trigger.New){' I got the error 'unknown variable'. Does the IDE not know, that Time__c is a custom object or do I have to declare it (in another way)?
- What does this code:
Set<String> TNames = new Set<String>();
... and: Do I need it here?
- Is there still something missing/incorrect?

Thank you for your advice!

 
Geoffrey J FlynnGeoffrey J Flynn
Hi, 
Check out this solution, you should be able to adapt it.  Same idea here, just using email to check dupes

http://www.sfdc99.com/2013/10/19/example-how-to-write-a-deduping-trigger-for-leads-and-contacts/

If you are really new, check out the entire site, it will really help you
mjohnson-TICmjohnson-TIC
You are trying to add date of the new trigger to an unsubstantiated Time__c record as opposed to a list of dates. Try this. 
 
trigger TimeValidation on Time__c (before insert) {
    
Set<date> tdates = new Set<date>();

for (Time__c tt : Trigger.New){
tdates.add(tt.Date__c);
}

try{   
for(Time__c t:[select id from Time__c where Date__c in: tdates]){
 Trigger.New[0].Name.addError('Duplicate Error!!');
}
}catch(exception e){
	//no records found with these dates
}

}