How to calculate sum of few fields in Edit View?

for example,
I have five fields (item 1, item 2, item 3, item 4, total)
I want the total to be calculated by entering item 1, item 2, item 3, and item 4 in Edit View
I tried the before save logic hook, but I still have to press save first, before I can get the total.
Is that possible to calculate the total in Edit View instantly ?

Thank you very much

@Airbus
Yes. You can use custom javascript code. Example fo load: modules/Accounts/metadata/editviewdefs.php

Thanks, but it doesn’t work, maybe there is something wrong with my coding?

In editviewdefs.php:

 'includes' => 
      array (
        0 => 
        array (
          'file' => 'custom/modules/<My_Module>/js/sum.js',
        ),
      ),
      'useTabs' => true,

In “total_c”, I added:

        array (
        'name' => 'total_c',
        'label' => 'LBL_TOTAL',
        'displayParams' =>
        array(
                        'javascript' => 'onchange=cal_total()', 
                     ),
               ),

js file:

        function cal_total(){

        var item1 = document.getElementById('item1_c').value;
        var item2 = document.getElementById('item2_c').value;
        var item3 = document.getElementById('item3_c').value;
        var item4 = document.getElementById('item4_c').value;
        var total = item1+item2+item3+item4;

        document.getElementById('total_c').value = total;
        }

Thanks

Hi,
shouldn’t it be something like:

$( document ).ready(function() {
	$( "#item1_c, #item2_c, #item3_c, #item4_c" ).change(function() {
		var total = $("#item1").val()+ $("#item2").val()+ $("#item3").val()+ $("#item4").val();
        $("#total_c").val(total);
	});
});

just include something like this in a js file and load the whole file instead:

'includes' => 
      array (
        0 => 
        array (
          'file' => 'modules/<some module>/<someName>.js',
        ),
      ),
2 Likes

Thanks,
I followed your instruction, but the Total still not being calculated in Edit View.
I’ve also tried to change the total = 1 for testing, but the Total doesn’t display 1 in Edit View

Thank you very much

Hi,
there are two possibilities: either the code itself does not work or it is not being loaded at all. I tested the js file shortly (using factory fields) and added some logging/casting:

$( document ).ready(function() {
console.log("custom js loaded");
$( "#name, #website" ).change(function() {
	var total = parseFloat($("#name").val()) + parseFloat($("#website").val());
	console.log("setting new total: " + total);
    $("#phone_fax").val(total);
  	});
});

when entering the EditView, you should see a line within the console (“custom js loaded”) and further messages appear when changing the name/website attributes.

1 Like

Thank you very much, it is working now