how to add a button to add product in yii2 ActiveForm

88 Views Asked by At

Hello am new to yii2 and am working on a project to record shop sales i would like to add a button to add product item for multiple purchase. please help

This is my _form code

<?php
    $form = ActiveForm::begin(['action' =>['sales/create'], 'id' => 'new-sales',   'method'=>'post',]); ?>
    <div class="container-fluid row">
        <div class="col-md-8">
            <?= 
               $form->field($model, 'product_name')
                     ->dropDownList(
                    arrayHelper::map(Product::find()->all(),'product_name','product_name'),
                ['prompt' => 'Select product', 'class' => 'form-control text-center', 'id'=>'pname']
            ) ?> 
        </div>
        <div class="col-md-4">
            <?= $form->field($model, 'quantity')->textInput([
                'type' => 'number', 'min' => 1, 'class' => 'form-control', 'id' => 'qnt'
            ]) ?>
        </div>
        <div class="col-md-6">
            <?= $form->field($model, 'amount')->textInput(['class'=> 'form-control']); ?>
        </div>
    </div>

is there a way i can also display amount based on product chosen and quantity before submit?

1

There are 1 best solutions below

1
Papa Joe Dee On

If I understand your post correctly, this looks like 2 different questions.

For producing additional line items dynamically, consider using a GridView widget to render your models. You can use extensions like the Krajee Editable to do in-place editing. He has pretty good demos on his site.


For an amount based on item and quantity, you can use jQuery to handle a change event. Start with a default quantity of 1 in your form model so the math works when you select the item. Also, give the amount field an id, e.g., 'id' = 'amt'(.

Then you can add something like this to your view:

<?php 
$script = <<< JS

$('#pname').on('change', function() {
    setamount();
});

$('#qnt').on('change', function() {
    setamount();
});

function setamount() {
  $.get('/product/get-amount', {pname : $('#pname').val(), qnt:$('#qnt').val()}, function(data) {
    $('#amt').html(data);
  });
}

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

Your Product controller action would be something like:

class ProductController extends Controller
{
...
   public function actionGetAmount($pname, $qnt) {
     $model = // find a product using $pname
     $amt = $model->item_price * $qnt;
     return $this->asJson($amt);
   }
...
}

There's probably a more efficient way because this requires a round trip to the database each time either value changes, and you should do some error trapping, but this should give you an idea.