You need to sign in to do that
Don't have an account?
Pete111
Update Picklist Value with Trigger
I am new to salesforce development and have been trying to do cross-object updates. I have worked through numerous errors, and am now getting no errors. The code compiles and seems to run just fine. Except that its not doing what its supposed to do. In a test App that I created i have an "Attack" object. I have a custom field called "Hit or Miss" (In order to create an Attack you must select a Unit Object to attack) When the Hit or Miss field is = "HIT" then the status of the Unit Object should go to "Dead" The status is a picklist with values Dead or Alive. Hopefully I have explained enough so that you can understand what it is I am trying to do. Here is my code.
trigger statusTrigger on Attack__c (after insert)
{
for(Attack__c a : Trigger.New)
{
if(a.Hit_or_Miss__c =='HIT!')
{
List<Unit_Type__c> unit = [SELECT Name,Status__c FROM Unit_Type__c WHERE Name = : 'a.Who_To_Attack__c'];
for(Unit_Type__c u : unit)
{
u.Status__c = 'Dead';
}
update unit;
}
else
{
//Do Nothing.
}
}
}
Can you see what im doing wrong?
trigger statusTrigger on Attack__c (after insert)
{
for(Attack__c a : Trigger.New)
{
if(a.Hit_or_Miss__c =='HIT!')
{
List<Unit_Type__c> unit = [SELECT Name,Status__c FROM Unit_Type__c WHERE Name = : 'a.Who_To_Attack__c'];
for(Unit_Type__c u : unit)
{
u.Status__c = 'Dead';
}
update unit;
}
else
{
//Do Nothing.
}
}
}
Can you see what im doing wrong?
My first advise: Becareful not to put SOQL and/or DML statement inside a FOR loop. This can easily make the code hit the governor limit.
Here is the revised of your code: Cheers
Boom
List<Unit_Type__c> 1stUnits = new List<Unit_Type__c>();
error : unexpected token: 'List'
Also, can you explain the reasoning for using the Set<id> setAttackIds? I think I understand but an additional explanation would be very much appreciated :)
Thanks in advance.
FYI: My complete code as it is right now.
trigger statusTrigger on Attack__c (after insert,after update)
{
Set<Id> setAttackIds = new Set<Id>();
for(Attack__c a : Trigger.New)
{
if(a.Hit_or_Miss__c =='HIT!') setAttackIds.add(a.Id);
}
List<Unit_Type__c> 1stUnits = new List<Unit_Type__c>();
for (Unit_Type__c u : [SELECT Name, Status__c FROM Unit_Type__c WHERE Name IN :setAttackIds])
{
u.Status__c = 'Dead';
1stUnits.add(u);
}
if (!1stUnits.isEmpty()) update 1stUnits;
}
the List<Unit_Type__c> is actually 'lstUnits' with a lowercase 'L' not number 1. Could you change that and see if it's ok?
boom