NewUser
NewUser

Reputation: 13323

Doing calculations in Yii

I have a database for InvoiceItems.The database is something like this

 === InvoiceItems ===
  id
  item_name
  quantity
  unit_price
  item_tax
  total

As I have made Model and CRUD for invoiceitems,I can easily insert and update the forms.Now as the business logic goes behind the database it needs to be automated.So according to the database when I will insert the quantity,unit_price and item_tax to the form,it should give me the result of total.

for example let us take the quantity as 20,
unit_price as 50,
item_tax as 10%,
so the result should be like this 20X50 = 1000+item_tax(10%)
                                        = 1000+100 = 1100;
                                        So in place of total 1100 should come.

Upvotes: 0

Views: 1184

Answers (2)

mwotton
mwotton

Reputation: 2200

Since you're using Yii, I'll assume you have jQuery loading. I'l also assume you have the tax value pre-populated with a percentage value (e.g. '10'), but this should be enough of a start if it's not.

$(document).ready(function(){
  $("#quantity, #unit_price").on('change',function(event){
    var $subtotal = $("#quantity").val() * $("#unit_price").val();
    var $total = $subtotal + ($subtotal  * $("#tax").val() / 100);
    $("#total").val($total);
  });
});

Upvotes: 2

bool.dev
bool.dev

Reputation: 17478

There are quite a few steps to do that:

  1. First create a button, that says something like Calculate Total
  2. When this button is clicked, call a javascript function, that reads the values of the inputs
  3. In this function calculate the total
  4. And then populate the total field

Edit:(without button)

  1. Call function to calculate total when the value has been entered, i.e. onBlur event, or maybe use onChange event.
  2. And then populate total field

Read more on Javascript events, to know which event is best suited for your application's flow. Read up on the differences, of the events i've mentioned.

Upvotes: 1

Related Questions