Getting null value when inserting data through Yii2 form - javascript

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())) {
.......
}

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?

Javascript doesn't work after ajax gridview filter reload yii2

I did a simple gridview table with filters on yii2, seems to be working great, but I noticed the javascript functions doesn't work after I apply any filter on the gridview table, i think its refreshing the whole page instead only refresh the table.
I did the $.pjax.reload method but it didn't work, this is how i applied the pjax reload method:
//inventariosearch-amb_id is the ID of one of my filterselects on the gridview
$("#inventariosearch-amb_id").on("pjax:end", function() {
$.pjax.reload({container:"#inventario_lista"}); //Reload GridView
});
Let me know if i applied wrong the method.
well, as I said I think the pjax is refreshing the whole page cause it changes my page title from this:
To this:
That's how I notice the changes and the javascript doesn't work properly anymore.
What can I do?.
My view index.php:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\grid\GridView;
use yii\grid\ActionColumn;
use yii\widgets\Pjax;
use yii\bootstrap4\Modal;
use app\models\Ambiente;
use app\models\TipoServicio;
use app\models\Empresa;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->registerJsFile("#web/js/inventario.js",[
'depends' => [
\yii\web\JqueryAsset::className()
]
]);
$this->title = 'Servidores';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="inventario-index">
<?php $this->beginBlock('bloque_titulo'); ?>
<div class="page-title-icon">
<i class="fa fa-archive icon-gradient bg-arielle-smile">
</i>
</div>
<div>
<?= Html::encode($this->title) ?>
<div class="page-title-subheading">
Lista de servidores
</div>
</div>
<?php $this->endBlock(); ?>
<p>
<?= Html::a('<i class="fa fa-plus"></i> AƱadir nuevo', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id'=>'inventario_lista','timeout'=> false,'clientOptions' => ['method' => 'POST','registerClientScript' => 'alert("lol")']]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $model,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'amb_id',
'value' => 'amb.amb_desc',
'filter' => Html::activeDropDownList($model, 'amb_id', ArrayHelper::map(Ambiente::find()->asArray()->all(), 'amb_id', 'amb_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
'inv_plataforma',
'inv_host_computername',
[
'attribute' => 'tise_id',
'value' => 'tise.tise_desc',
'filter' => Html::activeDropDownList($model, 'tise_id',ArrayHelper::map(TipoServicio::find()->orderby(['tise_desc'=>SORT_ASC])->asArray()->all(), 'tise_id', 'tise_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
[
'attribute' => 'emp_id',
'value' => 'emp.emp_desc',
'filter' => Html::activeDropDownList($model, 'emp_id',ArrayHelper::map(Empresa::find()->orderby(['emp_desc'=>SORT_ASC])->asArray()->all(), 'emp_id', 'emp_desc'), [
'class' => 'form-control',
'prompt' => '--- Seleccione ---'
])
],
//'inv_servicio',
//'inv_ip_admin',
//'inv_ip_servicio',
//'inv_ip_nfs',
//'sad_id',
//'usu_id_responsable_sistema',
//'usu_id_2doresponsable_sistema',
//'inv_modelo_servidor',
//'prov_id',
//'inv_serial_equipo',
//'inv_codigo_remedy',
//'inv_serial_dispositivo',
//'sop_id',
//'inv_version_so',
//'inv_alta_disponibilidad',
//'inv_ubicacion',
//'inv_ala',
//'inv_fila',
//'inv_rack',
//'inv_cpu_core',
//'inv_cpu_modelo',
//'inv_cpu_velocidad',
//'inv_gb_memoria',
//'hat_id',
//'inv_tipo_contrato_proveedor',
//'inv_responsable_funcional',
//'spa_id',
//'fv_id',
//'pr_id',
//'inv_observaciones',
//'inv_performance_review',
//'inv_performance_management',
//'inv_obsoleto',
//'inv_motivo_obsoleto',
//'inv_arbol',
//'inv_arbol_1er_nivel',
//'inv_fin_venta',
//'inv_fin_partes',
//'inv_fin_soporte',
//'inv_fecha_cons_obsoleto',
['class' => 'yii\grid\ActionColumn',
'buttons'=>[
'view'=>
function($url,$model,$key){
$btn = Html::button("<i class='fa fa-eye'></i>",[
'value'=>Yii::$app->urlManager->createUrl('inventario/view/'.$key),
'class'=>'serverview grid-action btn btn-info',
'title'=>'Ver datos del servidor',
'data-toggle'=> 'modal',
'data-target'=> '#modalviewserver',
]);
return $btn;
},
'update'=>function ($url,$model,$key) {
return Html::a('<i class="fa fa-edit"></i>', ['/inventario/update/'.$key], ['class'=>'btn btn-success grid-button']);
},
],
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php
Modal::begin([
'title' => '<h4>Ver servidor</h4>',
'id' => 'modalviewserver',
'size' => 'modal-lg',
]);
echo "<div id='viewservercontent'></div>";
Modal::end();
?>
My action controller:
public function actionIndex()
{
$model = new InventarioSearch();
$dataProvider = $model->search(Yii::$app->request->post());
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model
]);
}
And my JS (just in case):
$(document).ready(function ()
{
// $("#inventariosearch-amb_id").on("pjax:end", function() {
// $.pjax.reload({container:"#inventario_lista"}); //Reload GridView
// });
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
});
If you want your link to refresh whole page you have to remove your pjax.
Other way, try to set your javascript in pjax:success like this:
$(document).on('ready pjax:success', function(){
//your javascript here
$('.serverview').click(function()
{
$('#modalviewserver').appendTo("body").modal('show')
.find('#viewservercontent')
.load($(this).attr('value'));
});
})

Double Searching In Grid View yii2

I want to search field in my application. I have penerimaan_table. There are rm_code, quantity, bulan, price fields.
How to show my result like this:
rm_code bulan
k123 7
k123 4
k123 5
When I filter I want just show bulan 7 & 5
k123 7
k123 5
How can I do this?
This is my view:
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\export\ExportMenu;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\PenerimaanSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Penerimaan Raw Material';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="penerimaan-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Tambah Penerimaan Raw Material', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Import Penerimaan', ['import'], ['class' => 'btn btn-success']) ?>
</p>
<p><font color="red">Deskripsi Barang yang kosong merupakan Barang Baru!!</p></font>
<?php
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => [
// 'id',
'rm_code',
'rmCode.deskripsi_barang',
'saldo_awal',
'quantity',
'bulan',
//'price',
'total'
],
'showPageSummary' => true,
]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'kartik\grid\SerialColumn'],
// 'id',
'rm_code',
'rmCode.deskripsi_barang',
// 'saldo_awal',
'quantity',
'bulan',
[
'attribute' => 'price',
'label' => 'Price',
'footer' => $myAverage,
],
//'price',
[
'label' => 'Total',
'attribute' => 'total',
'pageSummary' => true,
// 'pageSummaryOptions' => ['id_layanan' => 'deskripsi'],
'value' => function ($model) {
if($model)
return $model->total ;
else
return 0;
}
],
['class' => 'kartik\grid\ActionColumn'],
],
'showPageSummary' => true,
]); ?>
<?php echo"Harga Rata-rata Barang adalah:";
$myAverage = 0;
$myTot =0;
$myCnt = 0;
$data = $dataProvider->getModels();
foreach ($data as $key => $value) {
$myTot += $value['price'];
$myCnt++;
}
if ($myCnt>0){
$myAverage = $myTot/$myCnt;
}
echo $myAverage; // your average displayed herre, you can place it wherever you want.
?>
<?php
$this->registerJs("
// 1. Dapatkan handle dari tabel gridview
table = $('div.grid-view > table');
// 2. Hitung kolom tertentu, pada contoh ini menghitung nilai total pada kolom ke 3
var sum = 0;
table.find('tbody').find('tr').each(function() {
sum += parseInt($(this).find('td:nth-child(4)').text());
});
// 3. Tampilkan hasil perhitungan pada tabel baris terakhir kolom ke 3
table.find('tfoot > tr > td:nth-child(4)').text(sum);
");
?>
</div>
Problem 1: the validators
Within your PenerimaanSearch-model remove the integer-validator for the bulan-field. And add two new ones as follows:
public function rules() {
//...
[['bulan'], 'integer', 'when'=>function($model) {
return strpos($model->bulan, '&') === false;
}],
[['bulan'], 'string', 'when'=>function($model) {
return strpos($model->bulan, '&') !== false;
}],
//...
}
This will only validate your field as an integer when no &is present. Otherwise it will use a string validator. The optimal way would be a regex-v& onle, but I'm sure you'll figure out how to do so.
Problem 2: functionality within the Search model
Again in the BulanSearch you can find the search()-method which is responsible for filtering the result by attributes. Remove all operations concerning the bulan-field and instead use the following:
public function search($params)
{
//...
if (!empty($this->bulan)) {
if (strpos($this->bulan, '&') !== false) {
$bulan = $this->bulan;
} else {
//filter with int
$bulan = explode('&', $this->bulan);
}
$this->andFilterWhere(['bulan'=>$bulan]);
}
//...
}
That should do the trick. The andFilterWhere decides itself whether to use an IN-condition (multiple values) or a regular comparison (single value).
This should do the trick! However, tell me if you have problems. I'll be happy to help!

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>

Populate value automatically in textbox within wbraganca dynamic form in yii2

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"]);
});
}

Categories

Resources