【问题标题】:Calculate the SUM of Fields in a dynamically changing form以动态变化的形式计算字段的总和
【发布时间】:2014-08-26 01:22:53
【问题描述】:

我目前正在尝试计算动态变化形式的总和。我目前拥有的是 Symfony2 表单集合,其中我将产品数量乘以单位成本 = ProductCost。到目前为止,这很好用。现在我需要添加一个表单的所有 ProductCost,并将生成的数字输入另一个字段(recipecost)。

我认为我需要的是一个 Foreach 循环,但不知道从哪里开始。

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 \Symfony\Component\HttpFoundation\Response(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 \Symfony\Component\HttpFoundation\Response(json_encode(array('success' => false, 'message' => 'Invalid product')));
    }
    $productCost = $product->getCostunit() * $fam;
    return new \Symfony\Component\HttpFoundation\Response(json_encode(array('success' => true, 'productCost' => $productCost)));
}

图片

老实说,我不知道从哪里开始,我花了最后几个小时试图弄清楚我应该使用 PHP 还是使用 Ajax 来做这件事,我目前有一个类似的函数,它作为最后按下提交按钮。看起来像这样:

Recipe.php/fixRecipeCost()

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

非常感谢任何帮助。我需要明确 ProductCost 字段的数量可能是 1 或 3000,因此不能简单地手动指定每个字段。

编辑

我正在尝试将其附加到我的 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;
    }

}

但是没有效果。我的日志中也没有错误。

【问题讨论】:

  • AJAX返回最新数据时为什么不重新计算SUM?这实际上取决于您如何返回数据,如果您有 100 个数据并且您只使用 AJAX 更改 1 个数据,那么我更喜欢使用 jQuery 重新计算 SUM。否则,您可以在 PHP 中重新计算。
  • 考虑使用 JS 框架进行计算。看看 Marionette、ReactJS 或 Angular。否则parent().parent().[...].find() 的东西看起来很丑。

标签: php jquery ajax forms symfony


【解决方案1】:

我同意 user26409021,您可以在每次 AJAX 调用返回时计算总和。这样的事情应该可以工作(假设您的“食谱成本”字段的 id 设置为“食谱成本”):

$(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);
}

【讨论】:

  • 这几乎是我已经解决的问题,但我没有将顶部部分拆分为它自己的功能。另外,如果部分看起来非常不同。我不能让你的代码工作。错误输入错误不断弹出,并且在控制台中,日志的每个部分都“未定义”。
  • 我刚刚编辑了我的答案,我意识到我没有将“this”变量更改为“field”变量。
猜你喜欢
  • 2016-03-08
  • 1970-01-01
  • 2013-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多