Skip to content
Advertisement

Calculate the SUM of Fields in a dynamically changing form

I am currently trying to calculate the total sum of a dynamically changing form. What I currently have is a Symfony2 collection of forms, in which I Multiply a product amount by a unitcost = ProductCost. This works great so far. Now I need to add all the ProductCost’s of a form and enter the resulting figure into another field (recipecost).

I think what I need is a Foreach loop, but don’t know where to start.

Calc.js

$(document).on('change', '.products, .amounts, .unit', function(event) {
var amount = $(this).parent().parent().find('.amounts').val();
var productId = $(this).parent().parent().find('.products').val();
var unit = $(this).parent().parent().find('.unit').val();
var productCostField = $(this).parent().parent().find('.product-costs');
var recipeCost = $(this).parent().parent().find('.recipecost');


console.log("Amount: " + amount + " - ProductID: " + productId + " - unit: " + unit);
if (amount == "" || productId == "" || unit == "") {
    // Don't make the Ajax call if missing one of the values
    return false;
}

// triggered every time an input field is changed
$.post(
        Routing.generate('calculate_cost'),
        {
            amount: amount,
            unit: unit,
            product: productId
        },
function(data) {
    data = JSON.parse(data);
    if (!data.success) {
        // An error was thrown in the controller
        alert(data.message);
    }
    else {
        // Update the corresponding productCost field using the data from the controller
        console.log("Product cost: " + data.productCost);
        productCostField.val(data.productCost);


var arr = document.getElementsByClassName('product-costs');
var tot=0;
for(var i=0;i<arr.length;i++){
    if(parseInt(arr[i].value))
        tot += parseInt(arr[i].value);
}
recipecostField.value = tot;
  }
 }
);
});

ProductRecipeController.php

public function getProductCostAction(Request $request) {

    $amount = $request->request->get('amount', null);
    $productId = $request->request->get('product', null);
    $unit = $request->request->get('unit', null);
    if (empty($amount) || empty($productId)) {
        return new SymfonyComponentHttpFoundationResponse(json_encode(array('success' => false, 'message' => 'Bad input')));
    }

    $em = $this->getDoctrine()->getManager();

    $product = $em->getRepository('BCInventoryBundle:Product')->find($productId);
    $u = $em->getRepository('BCInventoryBundle:Measures')->find($unit);

    $mass = new Mass($amount, $u->getUnit());
    $fam = $mass->toUnit('g');

    if (empty($product)) {
        return new SymfonyComponentHttpFoundationResponse(json_encode(array('success' => false, 'message' => 'Invalid product')));
    }
    $productCost = $product->getCostunit() * $fam;
    return new SymfonyComponentHttpFoundationResponse(json_encode(array('success' => true, 'productCost' => $productCost)));
}

Image

How I would like it to work Image

To be honest I have no idea where to begin with this, I’ve spent the last few hours trying to figure out if I should be doing it with PHP or with Ajax, I currently have a similar function which run’s as the Submit button is pressed in the end. Which looks like this:

Recipe.php/fixRecipeCost()

public function fixRecipecost() {
    $this->recipecost = 0;
    foreach ($this->product AS $pc) {
    $this->recipecost += $pc->getProductcost();
    $this->setRecipecost($this->recipecost);
    }
}

Any help much appreciated. I need to be clear that the amount of ProductCost fields could be 1 or 3000 so simply specifying each field by hand isn’t an option.

Edit

I have just being trying appending this to the end of my JS:

var arr = document.getElementsByClassName('product-costs');
var tot=0;
for(var i=0;i<arr.length;i++){
    if(parseInt(arr[i].value))
        tot += parseInt(arr[i].value);
}
recipecostField.value = tot;
    }

}

But is having no effect. No error’s in my log either though.

Advertisement

Answer

I agree with user26409021, you could calculate the sum every time the AJAX call returns. Something like this should work (assuming your “Cost for Recipe” field has the id set to “recipe-cost”):

$(document).on('change', '.products, .amounts, .unit', function(event) {
    updateProductCost(this);
});

function updateProductCost(field) {
    var amount = $(field).parent().parent().find('.amounts').val();
    var productId = $(field).parent().parent().find('.products').val();
    var unit = $(field).parent().parent().find('.unit').val();
    var productCostField = $(field).parent().parent().find('.product-costs');
    var recipeCost = $(field).parent().parent().find('.recipecost');

    console.log("Amount: " + amount + " - ProductID: " + productId + " - unit: " + unit);
    if (amount == "" || productId == "" || unit == "") {
        // Don't make the Ajax call if missing one of the values
        return false;
    }

    // triggered every time an input field is changed
    $.post(
            Routing.generate('calculate_cost'),
            {
                amount: amount,
                unit: unit,
                product: productId
            },
    function(data) {
        data = JSON.parse(data);
        if (!data.success) {
            // An error was thrown in the controller
            alert(data.message);
        }
        else {
            // Update the corresponding productCost field using the data from the controller
            console.log("Product cost: " + data.productCost);
            productCostField.val(data.productCost);
            calculateRecipeCost();
        }
    });
}

function calculateRecipeCost() {
    var totalCost = 0;
    $('.product-costs').each(function(index, value) {
        if ($.isNumeric($(this).val())) {
            totalCost = totalCost + parseFloat($(this).val());
        }
    });
    $('#recipe-cost').val(totalCost);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement