Populate value automatically in textbox within wbraganca dynamic form in yii2 - javascript

I've added wbraganca dynamic form in yii2. Within this form I'm trying to populate itemid a textbox when productname and batchno - two dropdowns are selected. I'm getting the value but unable to pass it in the textbox. Please help.
My Form looks like -
<div class="bills-form">
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
]); ?>
<?= $form->field($model, 'bills_partyname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Parties::find()->orderBy(['parties_partyname' => SORT_ASC,])->all(),'parties_partyname','partyDetails'),
'language' => 'en',
'options' => ['placeholder' => 'Select Party Name', 'id' => 'partyid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'transport')->textInput(['maxlength' => true, 'readOnly'=>true]) ?>
<?= $form->field($model, 'bills_ebillid')->textInput() ?>
<?= $form->field($model, 'bills_year')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Year::find()->orderBy(['yid' => SORT_DESC,])->all(),'year_year','year_year'),
'language' => 'en',
'options' => ['placeholder' => 'Select Year', 'id' => 'yearid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'console')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Console::find()->orderBy(['consoleid' => SORT_ASC,])->all(),'console','console'),
'language' => 'en',
'options' => ['placeholder' => 'Select Console','id' => 'consoleid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'num')->textInput() ?>
<?= $form->field($model, 'billno')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'billdate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Products</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 20, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsProductsales[0],
'formId' => 'dynamic-form',
'formFields' => [
'productname',
//'batchno',
'qty',
'free',
'total',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsProductsales as $i => $modelsProductsales): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Products</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelsProductsales->isNewRecord) {
echo Html::activeHiddenInput($modelsProductsales, "[{$i}]id");
}
?>
<div class="row">
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy(['productname' => SORT_ASC,])->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Productname', 'id' => 'productid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]free")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]total")->textInput(['maxlength' => true]) ?>
</div>
<?= $form->field($modelsProductsales, "[{$i}]itemid")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]batchno")->widget(DepDrop::classname(), [
'options'=>['id'=>'batchid'],
'pluginOptions'=>[
'depends'=>['productid'],
'placeholder'=>'BatchNo',
'url'=>Url::to(['/invoice/bills/subcat'])
]
]); ?>
<?= $form->field($modelsProductsales, "[{$i}]expdate")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]mrp")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]rate")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]discount")->textInput(['maxlength' => true]) ?>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<?= $form->field($model, 'billamount')->textInput() ?>
<?= $form->field($model, 'transport')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
And my javascript code is -
<?php
/* start getting the itemid and expdate */
$script = <<< JS
$(function(){
$('#productid').change(function(){
getItemid();
});
$('#batchid').change(function(){
getItemid();
});
var productid = $(this).val();
var batchid = $(this).val();
var getItemid = function(){
var productid = String($('#productid').val());
var batchid = String($('#batchid').val());
$.get('index.php?r=invoice/bills/get-for-itemid',{ productid : productid, batchid : batchid }, function(data){
//alert(data);
var data = $.parseJSON(data);
var getItemid = data;
$('#dynamic-[{$i}]itemid').val(getItemid["itemid"]);
});
} ;
});
JS;
$this->registerJs($script);
/* end getting the itemid and expdate */
?>
Please see the below screenshot. What I want -
Update
I've checked Yii2-dynamicforms and javascript and updated the 2 form fields(productname,batchno) on which the other are dependent like below -
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->label(false)->textInput(['onchange' => 'getItemdetails($(this))', 'onkeyup' => 'getItemdetails($(this))'])->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product','id' => 'prodname'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding">
<?= $form->field($modelsProductsales, 'batchno')->label(false)->textInput(['onchange' => 'getItemdetails($(this))', 'onkeyup' => 'getItemdetails($(this))'])->widget(DepDrop::classname(), [
'options'=>['id'=>'batchno'],
'pluginOptions'=>[
'depends'=>['prodname'],
'placeholder'=>'Batch No',
'url'=>Url::to(['/invoice/bills/subcat'])
]
]); ?>
But no idea about the javascript part. At present, the javascript looks like below -
<?
/* start getting the itemid */
$script = <<< JS
$(function(){
$('#productsales-{$i}-prodname').change(function(){
getItemid();
});
$('#productsales-{$i}-batchno').change(function(){
getItemid();
});
var prodname = $('#productsales-{$i}-batchno').val();
var batchno = $('#productsales-{$i}-batchno').val();
var getItemid = function(){
var prodname = String($('#productsales-{$i}-prodname').val());
var batchno = String($('#productsales-{$i}-batchno').val());
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : productsales-{$i}-prodname, batchno : productsales-{$i}-batchno }, function(data){
alert(data);
//var data = $.parseJSON(data);
//var getItemid = data;
//$('#productsales-{$i}-itemid').val(getItemid["itemid"]);
});
} ;
});
JS;
$this->registerJs($script);
/* end getting the itemid */
?>
Update:Implementing answer of Insaneskull
Form:Just copied from the answer.
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product', 'onchange' => 'getItemID($(this))'],
'pluginOptions' => [
'allowClear' => true
],
])->label(false);
?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding">
<?= $form->field($modelsProductsales, 'batchno')->widget(DepDrop::classname(), [
'options' => ['onchange' => 'getItemID($(this))'],
'pluginOptions'=>[
'depends'=> [Html::getInputID($modelsProductsales, "[{$index}]productname")],
'placeholder'=>'Batch No',
'url'=>Url::to(['/invoice/bills/subcat'])
]
])->label(false); ?>
</div>
And the JS function registered at the bottom of the form -
<?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product, batchno : batch }, function(data){
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
});
}
JS;
$this->registerJs($script);
/* end getting the itemid */
?>
And the error I'm getting -
Data is not getting selected in Select2 widget
Current Javascript
<?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product, batchno : batch }, function(data){
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
});
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>
error

_form.php
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product', 'onchange' => 'getItemID($(this))'],
'pluginOptions' => [
'allowClear' => true
],
])->label(false);
?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding">
<?= $form->field($modelsProductsales, '[{$i}]batchno')->widget(DepDrop::classname(), [
'options' => ['onchange' => 'getItemID($(this))'],
'pluginOptions'=>[
'depends'=> [Html::getInputID($modelsProductsales, "[{$i}]productname")],
'placeholder'=>'Batch No',
'url'=>Url::to(['/invoice/bills/subcat'])
]
])->label(false); ?>
</div>
JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product, batchno : batch }, function(data){
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
});
}

Related

Yii2 How to remove selected value from Select2 of a dynamic form?

I created a dynamic form using wbraganca / yii2-dynamicform to handle requests in my solution. I have couple fields like Item, Qty and Unit. I have a list of items loaded using ArrayHelper and I am using Kartik's Select2 widget to load the data.
_form.php
<?php
use backend\models\Item;
use backend\models\ItemCategory;
use backend\models\ItemUnit;
use backend\models\Jobs;
use common\models\User;
use kartik\depdrop\DepDrop;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\Requests */
/* #var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
var i = index;
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
});
});
';
$this->registerJs($js);
$itemCategory = ItemCategory::find()->where(['cat_status' => 'Active'])->all();
$catData = ArrayHelper::map($itemCategory, 'cat_id', 'cat_name');
if (!Yii::$app->user->identity->isAdmin) {
$modelJobs = Jobs::find()
->joinWith('myJobs')
->where(['ja_user_id' => Yii::$app->user->id, 'ja_status' => 'Active'])
->all();
} else {
$modelJobs = Jobs::find()
->where(['job_status' => 'In Progress'])
->all();
}
$jobs = ArrayHelper::map($modelJobs, 'job_id', function ($modelJobs) {
return $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
});
if (isset($_GET['cid'])) {
$cat_id = $_GET['cid'];
$subCate = Item::find()->where(['item_category' => $cat_id, 'item_status' => 'Active'])->all();
$invListData = ArrayHelper::map($subCate, 'item_id', 'item_title');
} else {
$cat_id = '';
$invListData = [];
}
if (isset($_GET['job']) && $_GET['job'] != null) {
$job_id = $_GET['job'];
$modelJobs = Jobs::find()->where(['job_id' => $job_id])->one();
$job = $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
} else {
$job_id = '';
}
$modelUnit = ItemUnit::find()->where(['unit_status' => 'Active'])->all();
$unit = ArrayHelper::map($modelUnit, 'unit_id', function ($modelUnit) {
return $modelUnit->unit_name . '(' . $modelUnit->unit_short_name . ')';
});
?>
<div class="requests-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?php $form->errorSummary($model); ?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($model, 'rq_cat_type')->widget(Select2::class, [
'data' => $catData,
'options' => ['placeholder' => '--Select Material Category--', 'value' => $cat_id, 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
"select2:select" => "function(params) {
console.log($(this).val());
window.history.pushState('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
window.location.replace('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
jQuery.pjax.reload({ container: '#loaderPjax', async: false });
}",
],
]);
?>
</div>
<div class="col-md-4">
<?php if (isset($_GET['job']) && $_GET['job'] != null) { ?>
<?= $form->field($model, "rq_job_no")->dropDownList([$job_id => $job], ['value' => $job_id]) ?>
<?php } else { ?>
<?php echo $form->field($model, 'rq_job_no')->widget(Select2::class, [
'data' => $jobs,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?php } ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_req_date')->widget(\yii\jui\DatePicker::class, [
//'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
'clientOptions' => [
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
'yearRange' => '1990:2030',
'minDate' => date('Y-m-d'),
],
'options' => ['class' => 'form-control', 'readOnly' => true, 'placeholder' => 'Enter the Item Required Date'],
]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_priority_type')->dropDownList(['Urgent' => 'Urgent', 'Normal' => 'Normal'], ['prompt' => '--Select Priority Type--']) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_approval_type')->dropDownList([1 => 'Aramco Approved Vendor Needed', 2 => 'Approved Aramco Submitted Needed', 3 => 'Warranty Certificate to be Collected', 4 => 'Long Lead Material',], ['prompt' => '--Select Type of Approval--']) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4>
</div>
<?php Pjax::begin(['id' => 'loaderPjax']); ?>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'rt_item',
'rt_qty',
'rt_unit',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress) { ?>
<div class="item panel panel-default">
<!-- widgetBody -->
<div class="panel-heading">
<h4 class="panel-title pull-left"></h4>
<span class="panel-title-address"></span>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]rt_id");
}
?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php } ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
<?php Pjax::end(); ?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'rq_remarks')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
</script>
The form is working perfectly, But I am facing some issues with the new requirement. The updated is to remove the selected value from the list. Which means if I select a value from the dropdown, the list should be updated without the selected value for next index in the dynamic form.
Tried couple of solutions with JQuery and javascript. The goal of requirement is to avoid duplicate entry of same value. Can anyone help me on this?

Call javascript function before submitting form

I need to call a Javascript function before submitting a form, this function generates 2 values (1 token and 1 hash), so I need to pass these values in 2 hidden fields.
JS Function: FULL/UPDATED
<script type="text/javascript">
//Generates the necessary content
$('#submitForm').click(function() {
PagSeguroBuscaHashCliente(); //Create Hash
PagSeguroBuscaBandeira(); //By field "pagseguro_cartao_numero" return flag card
PagSeguroBuscaToken(); //By 4 digits "pagseguro_cartao_numero" gen token card
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** TEST GENERATED VALUES **/
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
// var data = {
// hash: $('#pagseguro_cliente_hash').val(),
// token: $('#pagseguro_cartao_token').val()
// };
$('#pagseguro_cliente_hash').val(pagseguro_cliente_hash);
$('#pagseguro_cartao_token').val(pagseguro_cartao_token);
$('#sampleForm').submit();
}
</script>
View form:
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Assinatura;
use CWG\PagSeguro\PagSeguroAssinaturas;
$this->title = 'Assinatura';
$this->params['breadcrumbs'][] = $this->title;
$email = "xxxxxx#hotmail.com";
$token = "xxxxxxx";
// token gerado em 23/04/2020
$sandbox = false;
$pagseguro = new PagSeguroAssinaturas($email, $token, $sandbox);
//Sete apenas TRUE caso queira importa o Jquery também. Caso já possua, não precisa
$js = $pagseguro->preparaCheckoutTransparente(true);
echo $js['completo']; //Importa todos os javascripts necessários
?>
<div class="site-minhaconta">
<h1><?= Html::encode($this->title) ?></h1>
<!-- INICIO FORM -->
<?php $form = ActiveForm::begin([
'method' => 'post',
'id' =>'sampleForm'
])
?>
<div class="panel-body">
<?= $form->field($model, 'pagseguro_cartao_numero')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_mes')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_ano')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_cvv')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_nome')->textInput(['maxlength' => true]) ?>
<hr>
<?= $form->field($model, 'form_email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_cpf')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cliente_hash')->hiddenInput(['id' => 'pagseguro_cliente_hash'])->label(false)?>
<?= $form->field($model, 'pagseguro_cartao_token')->hiddenInput(['id' => 'pagseguro_cartao_token'])->label(false)?>
<div class="form-group">
<?= Html::button('Confirmar Assinatura', ['name'=>'submitForm',
'id' => 'submitForm', 'value'=>'submitForm', 'class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<!-- FINAL FORM -->
<script type="text/javascript">
//Generates the necessary content
$('#submitForm').click(function() {
PagSeguroBuscaHashCliente(); //Create Hash
PagSeguroBuscaBandeira(); //By field "pagseguro_cartao_numero" return flag card
PagSeguroBuscaToken(); //By 4 digits "pagseguro_cartao_numero" gen token card
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** TEST GENERATED VALUES **/
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
// var data = {
// hash: $('#pagseguro_cliente_hash').val(),
// token: $('#pagseguro_cartao_token').val()
// };
$('#pagseguro_cliente_hash').val(pagseguro_cliente_hash);
$('#pagseguro_cartao_token').val(pagseguro_cartao_token);
$('#sampleForm').submit();
}
</script>
</div>
Controller Action:
public function actionAssinatura()
{
$model = new \app\models\Assinatura();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->form_email = $_POST['Assinatura']['form_email'];
$model->form_cpf = $_POST['Assinatura']['form_cpf'];
$model->pagseguro_cliente_hash = $_POST['Assinatura']['pagseguro_cliente_hash'];
$model->pagseguro_cartao_token = $_POST['Assinatura']['pagseguro_cartao_token'];
return $this->render('plano_assinatura_process', [
'form_email' => $model->form_email,
'form_cpf' => $model->form_cpf,
'pagseguro_cliente_hash' => $model->pagseguro_cliente_hash,
'pagseguro_cartao_token' => $model->pagseguro_cartao_token,
]);
} else {
return $this->render('plano_assinatura_form', [
'model' => $model,
]);
}
}
Model file
public $pagseguro_cartao_numero;
public $pagseguro_cartao_mes;
public $pagseguro_cartao_ano;
public $pagseguro_cartao_cvv;
public $form_nome;
public $form_email;
public $form_cpf;
public $form_plano;
public $form_codplano;
public $pagseguro_cartao_token;
public $pagseguro_cliente_hash;
public function rules()
{
return [
[[
'pagseguro_cartao_numero',
'pagseguro_cartao_mes',
'pagseguro_cartao_ano',
'pagseguro_cartao_cvv',
'form_nome',
'form_email',
'form_cpf',
'form_plano',
//'form_codplano',
], 'required'],
[['pagseguro_cartao_token', 'pagseguro_cliente_hash'], 'safe'],
];
}
The hidden fields "pagseguro_cliente_hash" and "pagseguro_cliente_token" need to receive the variables js $ ('# pagseguro_cliente_hash'). Val () and $ ('# pagseguro_cartao_token'). Val () respectively.
How do you do that?
Generated JS by Payment gateway (UPDATE 2020-05-09)
<script type="text/javascript" src="https://stc.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js"></script><script type="text/javascript">PagSeguroDirectPayment.setSessionId("336d21fd502c41c982c55faf90e1eba9")</script>
<input type='hidden' id='pagseguro_cliente_hash'/>
<script type='text/javascript'>
function PagSeguroBuscaHashCliente() {
PagSeguroDirectPayment.onSenderHashReady(function(response){
if(response.status == 'error') {
console.log(response.message);
return false;
}
$('#pagseguro_cliente_hash').val(response.senderHash); //Hash estará disponível nesta variável.
console.log('Hash Cliente: ' + $('#pagseguro_cliente_hash').val());
});
}
</script>
<input type='hidden' id='pagseguro_cartao_token' />
<script type='text/javascript'>
function PagSeguroBuscaToken() {
PagSeguroDirectPayment.createCardToken({
cardNumber: $('#pagseguro_cartao_numero').val(),
brand: $('#pagseguro_cartao_bandeira').val(),
cvv: $('#pagseguro_cartao_cvv').val(),
expirationMonth: $('#pagseguro_cartao_mes').val(),
expirationYear: $('#pagseguro_cartao_ano').val(),
success: function(response) { console.log('Token: ' + response.card.token); $('#pagseguro_cartao_token').val(response.card.token)},
error: function(response) { console.log(response); },
});
}
</script>
Payment Gateway example form page:
<h2> Campos Obrigatórios </h2>
<p>Número do Cartão</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_numero-->
<input type="text" id="pagseguro_cartao_numero" value="4111111111111111"/>
<p>CVV do cartão</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_cvv-->
<input type="text" id="pagseguro_cartao_cvv" value="123"/>
<p>Mês de expiração do Cartao</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_mes-->
<input type="text" id="pagseguro_cartao_mes" value="12"/>
<p>Ano de Expiração do Cartão</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_ano-->
<input type="text" id="pagseguro_cartao_ano" value="2030"/>
<br/>
<button id="botao_comprar">Comprar</button>
<script type="text/javascript">
//Gera os conteúdos necessários
$('#botao_comprar').click(function() {
PagSeguroBuscaHashCliente(); //Cria o Hash identificador do Cliente usado na transição
PagSeguroBuscaBandeira(); //Através do pagseguro_cartao_numero do cartão busca a bandeira
PagSeguroBuscaToken(); //Através dos 4 campos acima gera o Token do cartão
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** FAÇA O QUE QUISER DAQUI PARA BAIXO **/
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
var data = {
hash: $('#pagseguro_cliente_hash').val(),
token: $('#pagseguro_cartao_token').val()
};
$.post('http://localhost/pagseguro/examples/assinando2.php', data, function(response) {
alert(response);
});
}
</script>
plano_assinatura_form:
<?php $form = ActiveForm::begin([
'method' => 'post',
'id' =>'sampleForm'
])
?>
<div class="panel-body">
<?= $form->field($model, 'pagseguro_cartao_numero')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_mes')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_ano')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_cvv')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_nome')->textInput(['maxlength' => true]) ?>
<hr>
<?= $form->field($model, 'form_email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_cpf')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cliente_hash')->hiddenInput(['id' => 'pagseguro_cliente_hash'])->label(false)?>
<?= $form->field($model, 'pagseguro_cartao_token')->hiddenInput(['id' => 'pagseguro_cartao_token'])->label(false)?>
<div class="form-group">
<?= Html::button('Confirmar Assinatura', ['name'=>'submitForm',
'id' => 'submitForm', 'value'=>'submitForm', 'class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<!-- FINAL FORM -->
<?php $this->registerJsFile(Yii::$app->request->baseUrl.'/test.js',['depends' => [\yii\web\JqueryAsset::className()]]); ?>
test.js:
$('#submitForm').click(function() {
// PagSeguroBuscaHashCliente(); //Create Hash
// PagSeguroBuscaBandeira(); //By field "pagseguro_cartao_numero"
return flag card
// PagSeguroBuscaToken(); //By 4 digits
"pagseguro_cartao_numero" gen token card
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** TEST GENERATED VALUES **/
pagseguro_cliente_hash = 'testHash';
pagseguro_cartao_token = 'testToken';
// var data = {
// hash: $('#pagseguro_cliente_hash').val(),
// token: $('#pagseguro_cartao_token').val()
// };
$('#pagseguro_cliente_hash').val(pagseguro_cliente_hash);
$('#pagseguro_cartao_token').val(pagseguro_cartao_token);
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
$('#sampleForm').submit();
}
actionAssinatura:
public function actionAssinatura()
{
$model = new \app\models\Assinatura();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->form_email = $_POST['Assinatura']['form_email'];
$model->form_cpf = $_POST['Assinatura']['form_cpf'];
$model->pagseguro_cliente_hash = $_POST['Assinatura']['pagseguro_cliente_hash'];
$model->pagseguro_cartao_token = $_POST['Assinatura']['pagseguro_cartao_token'];
return $this->render('plano_assinatura_process', [
'form_email' => $model->form_email,
'form_cpf' => $model->form_cpf,
'pagseguro_cliente_hash' => $model->pagseguro_cliente_hash,
'pagseguro_cartao_token' => $model->pagseguro_cartao_token,
]);
} else {
return $this->render('plano_assinatura_form', [
'model' => $model,
]);
}
}
fetch posted data in assinatura action :
C:\wamp64\www\basic\controllers\SiteController.php:139:
array (size=2)
'_csrf' => string 'C1spbi8HWaBqAO0w5ozFK6KOyKb20j0cRGR_j5t6vEg-FBE-
bXRs8gFZqVSOwp9xyOrl8sHleHUCMQv89CXxeQ==' (length=88)
'Assinatura' =>
array (size=9)
'pagseguro_cartao_numero' => string 'asdfasdf' (length=8)
'pagseguro_cartao_mes' => string 'asdfasdf' (length=8)
'pagseguro_cartao_ano' => string 'asdfasdf' (length=8)
'pagseguro_cartao_cvv' => string 'asdfasdf' (length=8)
'form_nome' => string 'asdfasdf' (length=8)
'form_email' => string 'asdfasdf' (length=8)
'form_cpf' => string 'asdfasdf' (length=8)
'pagseguro_cliente_hash' => string 'testHash' (length=8)
'pagseguro_cartao_token' => string 'testToken' (length=9)
In case of Yii
You should add below form structure using ActiveForm
<?php $form = ActiveForm::begin([
'id'=>'YourFormId'
]) ?>
//input fields and buttons
<?php ActiveForm::end() ?>
Simply add below code to execute your JS before form submitting
$('body').on('beforeSubmit',"#YourFormId",function() {
//javascript code here
});
return false; to stop form submitting
for more details Click Here

Yii2 - yii\grid\CheckboxColumn - Bulk Update and insert selected rows into another table

I have a table with these fields:
aca_class_subjects:
class_subject_id, class_subject_subject_id,
class_subject_class_group_id, class_subject_class_id
class_subject_id is the Primary Key and it is auto_increment.
class_subject_class_id and class_subject_class_group_id form a dependent dropdownlist.
class_subject_subject_id is from a table called aca_subjects and it will form the checkbox.
Controller: AcaClassSubjectsController
public function actionCreate()
{
$model = new AcaClassSubjects();
$searchModel = new AcaSubjectsSearch();
$searchModel->is_status = 0 ;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('create', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'model'=> $model,
]);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->class_subject_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
Model: AcaClassSubjects
public function attributeLabels()
{
return [
'class_subject_id' => Yii::t('aca', 'ID'),
'class_subject_subject_id' => Yii::t('aca', 'Subject'),
'class_subject_class_id' => Yii::t('aca', 'Class'),
'class_subject_class_group_id' => Yii::t('aca', 'Class Group'),
];
}
AcaSubjectsSearch
public function search($params)
{
$query = AcaSubjects::find()->where(['<>', 'is_status', 2]);
$dataProvider = new ActiveDataProvider([
'query' => $query, 'sort'=> ['defaultOrder' => ['subject_id'=>SORT_DESC]],
'pagination' => [ 'pageSize' => 5 ]
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'subject_id' => $this->subject_id,
]);
$query->andFilterWhere(['like', 'subject_name', $this->subject_name])
->andFilterWhere(['like', 'subject_code', $this->subject_code]);
return $dataProvider;
}
View
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php $form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]); ?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(),'class_group_id','class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange'=>'
$.get( "'.Url::toRoute('dependent/getclassmaster').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'class_subject_class_id').'" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]),'class_id','class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
</div>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?= GridView::widget([
'id'=>'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible'=> true,
'contentOptions' =>['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column) {
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]); ?>
<?= Html::input('hidden','keylists',$value='', $options=['id'=>'keylist']) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' =>'btn btn-success btn-block btn-lg','id'=>"button123"]) ?>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
My questions are
After selecting particular rows (subject_id) using checkboxes from Table aca_subjects, and also select the dropdownlist as shown in the diagram
How do I insert them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I update them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
How do I display a dialogue box when nothing is selected?
Note: class_subject_subject_id (checkbox in gridview),class_subject_class_id (dropdownlist), class_subject_class_group_id (dropdownlist)
When I clicked on submit, nothing goes to the database
Well, the question is a bit broad as you haven't shown any code related to solving your problem specifically so my wild guess is that you have a basic showstopper for collecting the class_subject_subject_id from the gridview. so i will suggest the javascript part in my answer where it submits the form with ajax.
But before i suggest you a solution you have a basic problem that you are wrapping the gridview with the form you are using to insert the subjects in the aca_class_subjects
Why?
Because if you wrap the Gridview with a form along with the gridview filters the GridView does not create its own hidden form that it uses for submitting the filter inputs for search in the GridView, and hence when you will try search by typing in the GridView filter input it would submit it to the action specified in your outer form that can have a different action like in your case.
So if you still want to use the ActiveForm do not wrap the Gridview inside the form keep it separate, and close it before you call the GridView::widget() but you have the button placed in the end of the Gridview and you dont want to change the design so change the code for the button from Html::submitButton() to Html::button() and keep it outside the ActiveForm that you have created. You can submit the form with javascript.
So your view code should look like below
<div class="col-xs-12" style="padding-top: 10px;">
<div class="box">
<?php
$form = ActiveForm::begin([
'id' => 'academic-level-form',
'enableAjaxValidation' => false,
'action'=>\yii\helpers\Url::to(['assign-subjects'])
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]);
?>
<div class="col-xs-12 col-lg-12 no-padding">
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(), 'class_group_id', 'class_group_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class Group ---',
'onchange' => '
$.get( "' . Url::toRoute('dependent/getclassmaster') . '", { id: $(this).val() } )
.done(function( data ) {
$( "#' . Html::getInputId($model, 'class_subject_class_id') . '" ).html( data );
}
);'
],
// 'disabled'=>'true',
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?=
$form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]), 'class_id', 'class_name'),
'language' => 'en',
'options' => ['placeholder' => '--- Select Class ---'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
<?=Html::input('hidden', 'keylists', $value = '', $options = ['id' => 'keylist']) ?>
<?php ActiveForm::end(); ?>
<div class="box-body table-responsive">
<h4><strong><u>Select Subject(s)</u></strong></h4>
<div class="course-master-index">
<?=
GridView::widget([
'id' => 'grid',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
[
'class' => 'yii\grid\CheckboxColumn',
'header' => Html::checkBox('selection_all', false, [
'class' => 'select-on-check-all',
'label' => 'All',
]),
'visible' => true,
'contentOptions' => ['style' => 'vertical-align:middle;width:30px'],
'checkboxOptions' => function($model, $key, $index, $column){
return ['value' => $model->subject_id];
}
],
['class' => 'yii\grid\SerialColumn'],
// 'id',
'subject_name',
],
]);
?>
<div class="form-group">
<?=Html::button('Submit', ['class' => 'btn btn-success btn-block btn-lg', 'id' => "button123"]) ?>
</div>
</div>
</div>
</div>
</div>
Now about the saving of the records.
You can get all the selected subjects that are in the grid view by using the following javascript code where you select all the checked checkboxes which have the name selection[]. Add the below code on top of your view
$reflect = new ReflectionClass($model);
$subjectId = $reflect->getShortName() . '[class_subject_subject_id][]';
$js = <<<JS
$("#button123").on('click',function(e){
e.preventDefault();
$("#academic-level-form").yiiActiveForm('submitForm');
});
$("#academic-level-form").on('beforeSubmit',function(e){
e.preventDefault();
// yii.getCsrfParam(),yii.getCsrfToken(),
let subjects=$("input[name='selection[]']:checked");
let subjectsSelected=subjects.length;
if(!subjectsSelected){
alert('select some subjects first');
}else{
let data=$(this).serializeArray();
$.each(subjects,function(index,elem){
data.push({name:"$subjectId",value:$(elem).val()})
});
let url=$(this).attr('action');
$.ajax({
url:url,
data:data,
type:'POST',
}).done(function(data){
alert(data);
}).fail(function(jqxhr,text,error){
alert(error);
});
}
return false;
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
Now if you have print_r(Yii::$app->request->post()) inside the actionAssignSubjects() in your controller where the form is submitting you can see the output of the posted variables and your subjects will be under the same model array that you are using for populating the dropdowns with the name class_subject_subject_id and all the selected subjects would be under this array. You can loop over them to save to your desired model.
I leave the rest of the work on you to do by your self and if you run into any problems you should post a separate question with the targetted code.

Sum of a gridview column in a textbox in yii2

I want to show the sum of a gridview column in a textbox. When the page loads, the sum should pass to the textbox.
I've written the following javascript code in my index.php file. But not getting the sum. The javascript code might not be correct. Please let me know how to do it -
index.php -
<?php
use yii\helpers\Html;
use yii\grid\GridView;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\sgledger\models\SellitemsgSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Sunglass Ledger';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="sellitemsg-index">
<h1>Sunglass Ledger</h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class= 'col-md-6'>
<?= GridView::widget([
'id' => 'purchasetable',
'dataProvider' => $dataProvider2,
'filterModel' => $searchModel2,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'poisg_id',
[
'attribute' => 'Date',
'value' => 'posg.posg_date'
],
'posg_invno',
[
'attribute' => 'Vendor',
'value' => 'posg.posg_vname'
],
//'poisg_sgname',
'poisg_qty',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
<div class= 'col-md-6'>
<?= GridView::widget([
'id' => 'selltable',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'ssgi_id',
[
'attribute' => 'Date',
'value' => 'sellsg.ssg_date'
],
'ssgi_invoiceno',
[
'attribute' => 'Customer',
'value' => 'sellsg.ssg_customer'
],
//'ssgi_sgname',
//'ssgi_price',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
</div>
<?php
/* start getting the textboxes */
$script = <<< JS
$(document).on('ready', function(e) {
var purgrid = purchasetable.getElementsByTagName('poisg_qty');
var total0 = 0;
for (var i = 0; i < purgrid.length; i++) {
var totp = purgrid[i].value
total0 = parseInt(total0) + parseInt(totp);
}
// ^ This number takes (n+1)th column
console.log('First table total value: ' + total0);
})
JS;
$this->registerJs($script);
/* end getting the textboxes */
?>
Present output -
Could be you can use showFooter for gridView
Firts you ca can calculate the value using the dataProvider
$yourTotal =0;
$numRow = 0;
foreach ($dataProvider->models as $key => $value) {
$yourTotal += $value['your_attribute'];
$numRow++;
}
Then in GridView you can set showFooter => TRUE and in the column you need you can add footer (and eventually footerOptions)
echo GridView::widget([
'dataProvider' => $dataProvider,
......
'showFooter'=>TRUE,
.....
'columns' => [
['class' => 'yii\grid\SerialColumn'],
......
[ 'attribute' => 'your_attribute',
'label' => 'Your Lable',
'footer' => $yourTotal,
'footerOptions' => ['style' => 'text-align:right;'],
],
........
and you can add you text using input
<?= Html::textInput('your_name', $yourTotal , options[]); ?>
or you can add a simple div
<div id='my_id'> <?= $yourTotal ?> </div>

Getting null value when inserting data through Yii2 form

I've added a textinput field in my production form. The unitprice fills up when I select productname field drop down. But when I'm saving the data, I'm getting following error -
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'unitprice' cannot be null
The SQL being executed was: INSERT INTO `bottle` (`usedate`, `useqty`, `productname`, `bottlename`, `unitprice`) VALUES ('2016-04-21', '12', 'CEFO', 'Enter', NULL)
The last "NULL" is the value for unitprice.
actionCreate in productionController-
public function actionCreate()
{
$model = new Production();
$productname = new Productnames();
$bottle = new Bottle();
$bottlename = new Bottlename();
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()))
{
$model->save();
//$bottle->attributes = $model->attributes;
$bottle->usedate = $model->productiondate;
$bottle->useqty = $model->prodqty;
$bottle->productname = $model->productname;
$bottle->bottlename = $productname->bottletype;
$bottle->unitprice = $bottlename->unitprice;
// $employee->emp_mobile = $model->emp_mobile;
$bottle->save();
return $this->redirect(['create']);
} else {
return $this->render('create', [
'model' => $model,
'bottle' => $bottle,
'productname' => $productname,
'bottlename' => $bottlename,
]);
}
}
Production _form
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\web\View;
use frontend\assets\XyzAsset;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\Productnames;
use kartik\depdrop\DepDrop;
use yii\helpers\Json;
use frontend\modules\production\models\Bottlename;
//XyzAsset::register($this);
/* #var $this yii\web\View */
/* #var $model frontend\modules\production\models\Production */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<!--<?= Html::a('Select Product', ['/production/productbatch/index'], ['class'=>'btn btn-primary']) ?> -->
<?= $form->field($model, 'productiondate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<!-- echo CHtml::button("(+)",array('title'=>"Select Product",'onclick'=>'js:selectproductforproduction();')); -->
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product Name', 'id' => 'catid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'batchno')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['catid'],
'placeholder'=>'Select BatchNo',
'url'=>Url::to(['/production/productbatch/subcat'])
]
]); ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<?= $form->field($productname, 'bottletype')->textInput() ?>
<?= $form->field($bottlename, 'unitprice')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$('#catid').change(function(){
var catid = $(this).val();
$.get('index.php?r=production/productnames/get-for-production',{ catid : catid }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#productnames-bottletype').attr('value',data.bottletype);
$('#bottlename-unitprice').attr('value',data.bottletype0.unitprice);
});
});
JS;
$this->registerJs($script);
?>
The action to get the data array
public function actionGetForProduction($catid)
{
$bottle = Productnames::find()->with('bottletype0')->where(['productnames_productname'=>$catid])->asArray()->one();
//$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1);
echo Json::encode($bottle);
This code works fine except the last unitprice. Please help.
You fotgot to add $bottlename->load(Yii::$app->request->post()) in if condition. So add like as,
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()) && $bottlename->load(Yii::$app->request->post())) {
.......
}

Categories

Resources