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>
Related
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'));
});
})
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.
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!
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())) {
.......
}
I have six fields which are editable in my Yii2 form widget. What i want to do is once i input integer values into editable fields calculate "Green leaf net weight" automatically based on the given input. my coding are work perfectly. But the problem is if i change already input value in the fields it'll not update the the "Green leaf net weight" read only field.
$(document).ready(function(){
var A = $('#A');
var B = $('#B');
var C = $('#C');
var D = $('#D');
var E = $('#E');
E.change(function(e){
var result = ((A.val() - B.val()) * C.val())/100;
var result2 = ((A.val() - B.val()) * D.val()) / 100;
var final = ((A.val() - B.val()) - result - result2) - E.val();
Math.round(final);
$('#F').val(final);
})
});
my form widget coding (updated code)
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'Gross_weight',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'A', **'class' => 'factors'** ]) ?>
<div class="panel panel-primary" style="padding: 10px;">
<div style="text-align: center; color: #008000;"><b>Deductions</b></div>
<?= $form->field($model, 'Bags_count',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput() ?>
<?= $form->field($model, 'Bags_weight',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'B', **'class' => 'factors'** ]) ?>
<?= $form->field($model, 'Course_leaf',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'C', **'class' => 'factors'**]) ?>
<?= $form->field($model, 'Water',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'D', **'class' => 'factors'**]) ?>
<?= $form->field($model, 'Boiled_leaf',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['id' => 'E',**'class' => 'factors'**]) ?>
</div>
<?= $form->field($model, 'Greanleaf_net_weight',[
'feedbackIcon' => [
'default' => 'shopping-cart',
'success' => 'ok',
'error' => 'exclamation-sign',
]
])->textInput(['disabled' => 'disabled', 'id' => 'F']) ?>
Thanks for everyone.
Inorder to execute the calculation on the change of all the input fields you have to add a class to all the input fields and use that class as the jQuery selector for change event.
<input id="A" class="factors" ... />
...
...
$(".factors").change(function(e) {
...
...
}
See Demo