Sum product volume and packages inside invoice

Sum product volume and packages inside invoice

I’m trying to create a custom function butI have 2 problems: 

1) In custom functions, how can I get the values of the list of products inserted and sum it?
Here’s a snippet of the code I’m working on: 

      set i(this.invoice.getInvoice()); //get the object of current invoice  
      set c(0); // double number variable 
      foreach (product p in i.getProducts()) 
           c+= p.getColli(); // colli is custom field inside each product 
     i.setColli(c); // Colli is the custom field inside invoice 

2) How can I call this function every time I save the invoice (to update field colli in invoice)?
With rules, I have no event saving the invoice, and i can’t call a function. 

Someone can help me?