I have a problem with a trigger.

I have this situation:

enter image description here

Question is: At each insertion of "Registrazione Visita", the owner's "Da pagare" field will be updated with the costs of visits made by that owner's animals.

My trigger now is:

trigger UpdateCosti on Registrazione_Visita__c (after insert) {          
    Set<id> TipologiaIds = new Set<id>();
    Set<id> animaliIds = new Set<id>();
    for (Registrazione_Visita__c  v : trigger.new) {
    Animale__c animal = [SELECT Name, Proprietario__r.Da_pagare__c FROM Animale__c WHERE Id in:animaliIds];
    Tipologia_visita__c tip = [SELECT Costo__c FROM Tipologia_visita__c WHERE Id in:TipologiaIds];
    animal.Proprietario__r.Da_pagare__c += tip.Costo__c;

but the owner's "Da Pagare" field does not update;

any help? Thank you.

2 Answers 2


As the "Da Pagare" field is on a different object to the one your trigger is handling, you will need to explcity update that record (or records) in your trigger.

Also consider that there can be multiple records involved so you need to code for that situation too.


You should explict call an update on Proprietario__c records.
You should also build a bulkified logic in your trigger and would be good to move it in an handler class. At the moment the SOQL on Animale__c will throw an exception if in the same transaction you create at least two Registrazione_Visita__c records related to different "Animali".
Lastly you don't need two SOQL since the trigger is on an object that has lookup fields to the other required objects.

trigger UpdateCosti on Registrazione_Visita__c (after insert) {          
    Map<Id, Proprietario__c> mapIdProprietario = new Map<Id, Proprietario__c>();
    for (Registrazione_Visita__c  registrazione : [SELECT Tipologia_visita__r.Costo__c, Animale__r.Proprietario__c, Animale__r.Proprietario__r.Da_pagare__c FROM Registrazione_Visita__c WHERE Id IN :Trigger.new]) {
        Proprietario__c proprietario = mapIdProprietario.get(registrazione.Animale__r.Proprietario__c);
        if (proprietario == null) {
            proprietario = new Proprietario__c(Id = registrazione.Animale__r.Proprietario__c);
            proprietario.Da_pagare__c = registrazione.Animale__r.Proprietario__r.Da_pagare__c != null : registrazione.Animale__r.Proprietario__r.Da_pagare__c : 0;
            mapIdProprietario.put(proprietario.Id, proprietario);
        proprietario.Da_pagare__c += registrazione.Tipologia_visita__r.Costo__c
    update mapIdProprietario.values();

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .