2017-09-14 223 views
0

我正在開發yii2中的發票。該發票已使用wbraganca\dynamicform\DynamicFormWidget動態添加items。這些項目分別具有quantityprice輸入,並且amount根據quantityprice的值自動更新。發票底部是total,它是發票每個itemamount的總和。當任何輸入字段即quantityprice發生變化時,total字段也會自動更新。我試圖想出一個Javascript我上線的代碼,但這隻會更新第一項amount,但其餘的都不起作用。下面是我對錶單代碼...根據yii2中輸入的值更新金額和總字段

_form.php

<?php 

use yii\helpers\Html; 
use kartik\widgets\ActiveForm; 
use wbraganca\dynamicform\DynamicFormWidget; 
use kartik\widgets\DatePicker; 
use yii\helpers\Url; 
use yii\helpers\ArrayHelper; 
use app\models\Tenant; 
use app\models\InvoiceItems; 
use app\models\FinancialAccounts; 

/* @var $this yii\web\View */ 
/* @var $model app\models\Invoices */ 
/* @var $form yii\widgets\ActiveForm */ 
?> 

<?php 
/* start getting the totalamount */ 
$script = <<<EOD 
    var getAmount = function() { 

     var qnty = $(".qnty").val(); 
     var price = $(".price").val(); 
     var amount = 0; 

     amount = parseInt(qnty) * parseInt(price); 

     //Assign the sum value to the field 
     $(".amount").val(amount); 
    }; 

    $(".price").on("change", function() { 
     getAmount(); 
    }); 
EOD; 
$this->registerJs($script); 
/*end getting the totalamount */ 
?> 

<div class="invoices-form"> 

    <?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?> 

    <fieldset> 

     <legend>Invoice Details</legend> 

     <div class="form-group kv-fieldset-inline"> 
      <div class="col-sm-3"> 
       <?= $form->field($modelInvoice, 'tenant_id')->dropDownList(ArrayHelper::map(Tenant::find()->select(['tenant_id', 'first_name', 'last_name', 'address'])->all(), 'tenant_id', 'displayName'), 
       [ 
        'prompt'=>'Select Tenant', 'class' => 'form-control inline-block', 
        'onchange'=>' 
         $.post("'.Yii::$app->urlManager->createUrl('lease/list-lease?tenant_id=').'"+$(this).val(), function(data) { 
          $("select#lease").html(data); 
         }); 
        ' 
       ]) ?> 
      </div> 

      <div class="col-sm-3"> 
       <?php 
       $dataLease=ArrayHelper::map(\app\models\Lease::find()->asArray()->all(), 'lease_id', 'leaseDetails'); 
       echo $form->field($modelInvoice, 'lease') 
        ->dropDownList(
         $dataLease,   
         ['id'=>'lease'] 
        ); 
      ?> 
      </div> 

      <div class="col-sm-3"> 
       <?= $form->field($modelInvoice, 'date')->widget(DatePicker::classname(), ['options' => ['placeholder' => 'Enter Invoice date ...'], 'pluginOptions' => ['autoclose'=>true, 'format' => 'yyyy-mm-dd', 'endDate' => '0d']]) ?> 
      </div> 

      <div class="col-sm-3"> 
       <?= $form->field($modelInvoice, 'due_date')->widget(DatePicker::classname(), ['options' => ['placeholder' => 'Enter due date ...'], 'pluginOptions' => ['autoclose'=>true, 'format' => 'yyyy-mm-dd', 'startDate' => '0d']]) ?> 
      </div> 

      <div class="col-sm-3"> 
       <?= $form->field($modelInvoice, 'invoice_number')->textInput(['maxlength' => true]) ?> 
      </div> 
     </div>   

    </fieldset> 

    <fieldset> 

     <legend>Invoice Line Items</legend> 

     <?php DynamicFormWidget::begin([ 
      'widgetContainer' => 'dynamicform_wrapper', 
      'widgetBody' => '.container-items', 
      'widgetItem' => '.invoice-item', 
      'limit' => 10, 
      'min' => 1, 
      'insertButton' => '.add-item', 
      'deleteButton' => '.remove-item', 
      'model' => $modelsInvoiceItem[0], 
      'formId' => 'dynamic-form', 
      'formFields' => [ 
       'Items', 
      ], 
     ]); ?> 

     <table class="table table-bordered table-striped"> 
      <thead> 
       <tr> 
        <th>Invoice Item</th> 
        <th>Description</th> 
        <th>Quantity</th> 
        <th>Price (Kshs)</th> 
        <th>Account</th> 
        <th>Amount</th> 
        <th class="text-center" style="width: 5%;"> 
         <button type="button" class="add-item btn btn-success btn-xs"><span class="fa fa-plus"></span></button> 
        </th> 
       </tr> 
      </thead> 
      <tbody class="container-items"> 
      <?php foreach ($modelsInvoiceItem as $indexItem => $modelInvoiceItem): ?> 
       <tr class="invoice-item"> 
        <td class="vcenter"> 
         <?php 
          // necessary for update action. 
          if (! $modelInvoiceItem->isNewRecord) { 
           echo Html::activeHiddenInput($modelInvoiceItem, "[{$indexItem}]id"); 
          } 
         ?> 
         <?= $form->field($modelInvoiceItem, "[{$indexItem}]item_id")->label(false)->dropDownList(ArrayHelper::map(InvoiceItems::find()->select(['item_id', 'item'])->all(), 'item_id', 'item'),['class' => 'form-control inline-block', 'prompt'=>'Select Invoice Item']) ?> 
        </td> 
        <td class="vcenter"> 
         <?= $form->field($modelInvoiceItem, "[{$indexItem}]desc")->label(false)->textInput(['maxlength' => true]) ?> 
        </td> 
        <td class="vcenter"> 
         <?= $form->field($modelInvoiceItem, "[{$indexItem}]qnty")->label(false)->textInput(['class' => 'qnty']) ?> 
        </td> 
        <td class="vcenter"> 
         <?= $form->field($modelInvoiceItem, "[{$indexItem}]price")->label(false)->textInput(['class' => 'price']) ?> 
        </td> 
        <td class="vcenter"> 
         <?= $form->field($modelInvoiceItem, "[{$indexItem}]account_id")->label(false)->dropDownList(ArrayHelper::map(FinancialAccounts::find()->select(['account_id', 'account_name'])->all(), 'account_id', 'account_name'),['class' => 'form-control inline-block', 'prompt'=>'Select Account']) ?> 
        </td> 
        <td class="vcenter"> 
         <?= $form->field($modelInvoiceItem, "[{$indexItem}]amount")->label(false)->textInput(['class'=>'amount','readOnly'=> true]) ?> 
        </td> 
        <td class="text-center vcenter" style="width: 5%; verti"> 
         <button type="button" class="remove-item btn btn-danger btn-xs"><span class="fa fa-minus"></span></button> 
        </td> 
       </tr> 
      <?php endforeach; ?> 
      </tbody> 
      <tbody> 
       <tr> 
        <td></td> 
        <td></td> 
        <td></td> 
        <td></td> 
        <td>Total</td> 
        <td class="total"> 
         <?= $form->field($modelInvoice, "total")->label(false)->textInput(['class'=>'total','readOnly'=> true]) ?> 
        </td> 
        <td></td> 
       </tr> 
      </tbody> 
     </table> 

     <?php DynamicFormWidget::end(); ?> 

    </fieldset> 


    <div class="col-sm-offset-3 col-sm-9"> 
     <?= Html::submitButton($modelInvoice->isNewRecord ? 'Create' : 'Update', ['class' => $modelInvoice->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
     <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> 
    </div> 

    <?php ActiveForm::end(); ?> 

</div> 

具體來說,這是Javascript代碼

<?php 
/* start getting the totalamount */ 
$script = <<<EOD 
    var getAmount = function() { 

     // var items = $(".item"); 
     // var qnty = $(elem).find(".qnty").val(); 
     var qnty = $(".qnty").val(); 
     var price = $(".price").val(); 
     // var price = $(elem).find(".price").val(); 
     var amount = 0; 

     amount = parseInt(qnty) * parseInt(price); 

     // items.each(function (index, elem) { 
     //  var priceValue = $(elem).find(".sumPart").val(); 
     //  //Check if priceValue is numeric or something like that 
     //  sum = parseInt(sum) + parseInt(priceValue); 
     // }); 
     //Assign the sum value to the field 
     $(".amount").val(amount); 
    }; 

    //Bind new elements to support the function too 
    $(".price").on("change", function() { 
     getAmount(); 
    }); 
EOD; 
$this->registerJs($script); 
/*end getting the totalamount */ 
?> 

這裏是我一起工作的形式的截圖: Screen Shot of the Invoice

我不好用Javascript因此我不明白mos代碼的代碼,但我得到了信息的想法和流程。請幫助我在這裏能做些什麼。 謝謝。

+0

[這將有助於(https://stackoverflow.com/questions/44122573/how-sum-dynamic-fields-using-wbraganca-yii2-dynamicform/ 44141184#44141184)。 –

回答

1

您可以對類選擇符(「.class」)使用$符號。所以你得到回報。

jQuery val方法:

獲取所述第一元件的集合中匹配的元素的當前值或設置每個匹配的元素的值。

您可以使用行索引使不同的元素具有唯一性。

嘗試

$(".price").on("change", function(event) { 
    getAmount(event); 
}); 

function getAmount(event) { 
    var priceElement = event.target; 
    // extract row index from priceElement's id 
    // use row index to find elements with id selector ("#elementId") 
}; 
+0

感謝您的回答@Sui。到底如何提取行元素? 'Javascript'不是很好,如果你可以提供一個工作代碼,我會很感激。 – japheth

+0

我剛剛檢查了頁面源,我發現輸入字段的編號是'invoiceline-0-price','invoiceline-1-price'等。中心值是動態的,取決於索引。如何在Javascript中執行相同的操作? – japheth

+0

@japheth,你可以使用[substr()方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr): 'priceElement.attr('然後,你可以使用字符串連接來獲取其他元素的id,比如''invoiceline-'+ priceElement.attr('id')。substr(12,1)+' - 'substr(12,1)' –

0

基於以上@Sui夢的解決方案,並從網上查詢其他地方,這是我能夠做到最後。我只更新了腳本,一切工作得很好:

<?php 
/* start getting the totalamount */ 
$script = <<<EOD 
    var getAmount = function() { 

     var items = $(".invoice-item"); 
     var amount = 0; 
     var total = 0; 

     items.each(function (index, elem) { 
      var qnty = $(elem).find(".qnty").val(); 
      var price = $(elem).find(".price").val(); 
      //Check if qnty and price are numeric or something like that 
      amount = parseInt(qnty) * parseInt(price); 

      //Assign the amount value to the field 
      $(elem).find(".amount").val(amount); 

      var amountValue = $(elem).find(".amount").val(); 

      total = parseInt(total) + parseInt(amountValue); 

      $(".total").val(total); 
     }); 
    }; 

    //Bind new elements to support the function too 
    $(".container-items").on("change", function() { 
     getAmount(); 
    }); 
EOD; 

$this->registerJs($script); 
?>