I am making a cost accounting application. And then in a case, I have success to sum data, but when I want get a average, I get an error. I have to try too much code in here, but nothing result.
How can I do to get average from my data here?
This is my view:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use kartik\grid\GridView;
use yii\data\ActiveDataProvider;
use backend\models\Penerimaan;
use yii\web\App;
/* #var $this yii\web\View */
/* #var $model backend\models\Triwulan */
$this->title = $model->rm_code;
$this->params['breadcrumbs'][] = ['label' => 'Triwulan', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="triwulan-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->rm_code], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->rm_code], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'rm_code',
'deskripsi_barang',
],
]) ?>
<?= GridView::widget([
'dataProvider'=>new yii\data\ActiveDataProvider([
'pagination'=>false,
'query'=>$model->getPenerimaans(),
]),
'columns'=>[
['class' => 'kartik\grid\SerialColumn'],
[
'attribute'=>'bulan',
'pageSummary' => 'Jumlah',
], [
'attribute' => 'price' ,
// 'pageSummary' => 20 - 20 - $model->idDhs->idMatakuliah->sks,
'pageSummary' =>(true),
'value' => function ($model) {
if($model)
return $model->price;
}
],
// ['class' => 'kartik\grid\ActionColumn'],
// 'product',
// 'qty'
],
'showPageSummary' => true,
])
?> Harga rata-rata barang adalah:
<?php
//$db= Yii::$app->db;
// $command=$db->createCommand('Select * from penerimaan where id=408');
// $penerimaan = $command->queryAll();
// foreach ($penerimaan as $penerimaans) {
// echo $penerimaans['price'];
// } echo "<br>";
// $users = Yii::$app->db->createCommand('SELECT * FROM penerimaan where rm_code=id')->queryAll();
//$connection= Yii::$app->db;
// $users= $connection->createCommand('SELECT * FROM penerimaan where rm_code=id')->execute();
// var_dump($users);
// $participantProvider = new ActiveDataProvider([
// 'query' => Penerimaan::find()->where('price',$model),
//]);
// $hasil = 14 /$participantProvider->getTotalCount();
// echo $hasil;echo "</br>";
?>
</div>
</div>
This was the already answered question and was correct answer, but I think you are not able to figure-out the solution.
Now add this code on your view page and try
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use kartik\grid\GridView;
use yii\data\ActiveDataProvider;
use backend\models\Penerimaan;
use yii\web\App;
/* #var $this yii\web\View */
/* #var $model backend\models\Triwulan */
$this->title = $model->rm_code;
$this->params['breadcrumbs'][] = ['label' => 'Triwulan', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="triwulan-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->rm_code], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->rm_code], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'rm_code',
'deskripsi_barang',
],
]) ?>
<?php
$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.
?>
<?= GridView::widget([
'dataProvider'=>new yii\data\ActiveDataProvider([
'pagination'=>false,
'query'=>$model->getPenerimaans(),
]),
'columns'=>[
['class' => 'kartik\grid\SerialColumn'],
[
'attribute'=>'bulan',
'pageSummary' => 'Jumlah',
],
[
'attribute' => 'price' ,
'pageSummary' =>(true),
'value' => function ($model) {
if($model)
return $model->price;
}
],
],
'showPageSummary' => true,
])
?>
</div>
</div>
Related
Is it possible to call action from a controller in different view ?
example
I have 2 controllers : Post and Blog , so I want to call actionCreate from post but inside blog view not in post view. I have 2 views and 2 controllers :
view :
1. views/blog/view
2. views/post/view
controller
1. controllers/blogController.php
2. controllers/postController.php
controllers/PostController.php :
public function actionCreate()
{
$model_Post = new Post();
if ($model_Post->load(Yii::$app->request->post()) && $model_Post->save()) {
return $this->redirect(['view', 'id' => $model_Post->Post_id]);
} else {
return $this->render('/blog/view', [
'model_Post' => $model_Post,
]);
}
}
views/blog/view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Likectt */
$this->title = $model->Blog_id;
?>
<div class="blog-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Blog_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Blog_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'Blog_id',
'Blog_title',
'Blog_text',
'User_id',
'Category_id',
],
]) ?>
<?= Yii::$app->runAction('PostController/actionCreate', ['model_Post'=>$model_Post]);?>
</div>
Yes you can do that :
In you blog view :
Yii::$app->runAction('postController/actionCreate', ['param1'=>'value1', 'param2'=>'value2']);
I've one select2 form field, two datepickers and a search button in productnames index file. It is only to search data I'm unable to get the data selected in the select2 widget and pass it to controller which in turn can search other models.
index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use kartik\select2\Select2;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use frontend\modules\sbbtdtproduct\models\Productnames;
use yii\helpers\Json;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\sbbtdtproduct\models\ProductnamesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Productnames';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="productnames-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<div class="row">
<div class="form-group">
<div class="col-xs-5 col-sm-5 col-lg-5" >
<?php
echo Select2::widget([
'model' => $model,
'attribute' => 'productnames_productname',
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'options' => ['placeholder' => 'Select Product'],
'pluginOptions' => [
'allowClear' => true
],
//'productname' => $productname,
]);
?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'Start Date',
'attribute' => 'from_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'End Date',
'attribute' => 'to_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1" >
<?= Html::a('Search', ['/sbbtdtproduct/production/index','productname' => $model['productnames_productname']], ['class'=>'btn btn-primary']) ?>
</div>
</div>
</div>
</div>
production controller action
public function actionIndex($productname)
{
$productname = yii::$app->request->get('productnames_productname');
$searchModel = new ProductionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $productname);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
productionsearch model
public function search($params,$productname)
{
$query = Production::find()
->where(['productname' => $productname]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'productionid' => $this->productionid,
'productiondate' => $this->productiondate,
'itemid' => $this->itemid,
'prodqty' => $this->prodqty,
]);
$query->andFilterWhere(['like', 'productname', $this->productname])
->andFilterWhere(['like', 'batchno', $this->batchno]);
return $dataProvider;
}
error -
update -
Database Log
The data base Log shows that no value has been passed from search model.
I can see the value selected in select2 or datepicker as below, but it's not passing to the controller.
1.on your view page
You have not added form tag, so other parameters will not get posted, you must add everything inside form tag and submit that form, as follows
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use kartik\select2\Select2;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use frontend\modules\sbbtdtproduct\models\Productnames;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\sbbtdtproduct\models\ProductnamesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Productnames';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="productnames-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]);
$form = ActiveForm::begin([
'action' => ['/sbbtdtproduct/production/index'],
'method' => 'post',
'options' => ['data-pjax' => true],
'enableClientValidation' => FALSE
]);
?>
<div class="row">
<div class="form-group">
<div class="col-xs-5 col-sm-5 col-lg-5" >
<?php
echo Select2::widget([
'model' => $model,
'attribute' => 'productnames_productname',
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'options' => ['placeholder' => 'Select Product'],
'pluginOptions' => [
'allowClear' => true
],
//'productname' => $productname,
]);
?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'Start Date',
'attribute' => 'from_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= DatePicker::widget([
'name' => 'End Date',
'attribute' => 'to_date',
'value' => '2014-01-31',
'template' => '{addon}{input}',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1" >
<?= Html::submitButton('Search', ['class'=>'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
2.Controller
now inside your controller you can access parametes as follows
public function actionIndex()
{
$productname = Yii::$app->request->post('productnames_productname');
$searchModel = new ProductionSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $productname);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
I have two tables -
1. rmtemplate
id, productname, rmname, qty
2. rmname
rmid,rmname,min,unitcost
The query I want to run is -
SELECT id,productname,rmtemplate.rmname,qty,rmtemplate.qty * rmname.unitcost as cost
FROM `rmtemplate`
left join rmname on rmtemplate.rmname = rmname.rmname
In Yii2 I've joined two tables with no problem. The unitcost is showing without any trouble. But when I try to multiply rmtemplate.rmname to rmname.unitcost it returns error - 'Getting unknown property: frontend\models\Rmtemplate::cost'
RmtemplateSearch.php -
public $cost;
public function rules()
{
return [
[['id'], 'integer'],
[['productname', 'rmname', 'qty', 'unitcost','cost'], 'safe'],
];
}
$query = Rmtemplate::find()
->joinWith(['unitcost'])
->select(['id','productname','rmtemplate.rmname','qty', '(rmtemplate.qty * rmname.unitcost) as cost']);
Rmtemplate Model
public function getUnitcost()
{
return $this->hasOne(Rmname::className(), ['rmname' => 'rmname']);
}
Rmtemplate index.php
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use frontend\models\Rmtemplate;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\rmprod\models\RmtemplateSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Rmtemplates';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="rmtemplate-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Rmtemplate', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'kartik\grid\CheckboxColumn'],
'id',
//'productname',
[
'attribute'=>'productname',
'filterType'=>GridView::FILTER_SELECT2,
'filter'=>ArrayHelper::map(Rmtemplate::find()->orderBy(['productname' => SORT_ASC])->asArray()->all(), 'productname', 'productname'),
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Charge Name'],
],
'rmname',
'qty',
[
'attribute' => 'unitcost',
'value' => 'unitcost.unitcost',
],
'cost',
['class' => 'kartik\grid\ActionColumn'],
],
]); ?>
</div>
Please let me know if any further input required.
In this case the sql query in the search model is -
$query = (new Query())
->select (['billdate','billno','bills_partyname','billamount'])
->from('bills')
->where(['between', 'billdate', 'from_date', 'to_date']);
I've added a daterangepicker in the index.php file. The code is -
<?= DatePicker::widget([
'name' => 'from_date',
'value' => '2014-01-01',
'type' => DatePicker::TYPE_RANGE,
'name2' => 'to_date',
'value2' => '2016-01-01',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
]);
?>
Controller
public function actionIndex()
{
$searchModel = new PartiesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Parties model.
* #param integer $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
index.php looks like
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\date\DatePicker;
use kartik\daterange\DateRangePicker;
use kartik\form\ActiveForm;
//use dosamigos\datepicker\DatePicker;
use frontend\modules\districtreport\models\ExpartiesSearch;
/* #var $this yii\web\View */
/* #var $searchModel frontend\modules\districtreport\models\PartiesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Parties';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="parties-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <p>
<?= Html::a('Create Parties', ['create'], ['class' => 'btn btn-success']) ?>
</p> -->
<!-- <div class="custom-filter">
Date range:
<input name="start" />
<input name="end" />
</div> -->
<?= '<label class="control-label">Select Date Range</label>'; ?>
<?= DatePicker::widget([
'model' => $searchModel,
'attribute' => 'from_date',
'value' => '2014-01-01',
'type' => DatePicker::TYPE_RANGE,
'attribute2' => 'to_date',
'value2' => '2016-01-01',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
]);
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'export' => false,
'columns' => [
// [
// 'class' => 'kartik\grid\ExpandRowColumn',
// 'value' => function($model, $key, $index, $column){
// return GridView::ROW_COLLAPSED;
// },
// 'detail' => function($model, $key, $index, $column){
// $searchModel = new ExpartiesSearch();
// $searchModel-> parties_district = $model['district'];
// $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// return Yii::$app->controller->renderPartial('_exparties', [
// 'searchModel' => $searchModel,
// 'dataProvider' => $dataProvider,
// ]);
// },
// ],
// 'district',
// 'sell',
// 'collection',
'billdate',
'billno',
'bills_partyname',
'billamount',
],
]); ?>
</div>
This is not working. Please tell me what needs to be done.
Somthing like this
In View before GridView
<?php
$form = ActiveForm::begin([
'method' => 'get',
'enableClientScript' => false
]);
?>
<?= '<label class="control-label">Select Date Range</label>'; ?>
<?= DatePicker::widget([
'model' => $searchModel,
'attribute' => 'from_date',
'value' => '2014-01-01',
'type' => DatePicker::TYPE_RANGE,
'attribute2' => 'to_date',
'value2' => '2016-01-01',
'pluginOptions' => [
'autoclose'=>true,
'format' => 'yyyy-mm-dd'
]
]);
?>
<?php echo Html::submitButton('Search') ?>
<?php ActiveForm::end(); ?>
In Controller
public function actionIndex(){
$searchModel = new PartiesSearch();
$dataProvider = $searchModel->search(\Yii::$app->request->get());
return $this->render('index', compact('dataProvider', 'searchModel'));
}
In Your Search Model
class PartiesSearch extends Parties
{
public $from_date;
public $to_date;
//add rule
public function rules(){
return [
//... your rules,
[['from_date', 'to_date'], 'safe']
];
}
//... some code
public function search($params = []){
$query = (new Query())
->select (['billdate','billno','bills_partyname','billamount'])
->from('bills');
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
if( !($this->load($params) && $this->validate()) ){
return $dataProvider;
}
if($this->from_date && $this->to_date)
$query->where(['between', 'billdate', $this->from_date, $this->to_date]);
return $dataProvider;
}
from_date is come by post/Get method Try this
$query = (new Query())->select (['billdate','billno','bills_partyname','billamount'])->from('bills')->where(['between', 'billdate', $_POST['from_date'], $_POST['to_date']]);
You are not using model to create date range picker so either use model or change name from
'name' => 'from_date'
to
'name' => 'PartiesSearch[from_date]'
*and similar for to_date
When I'm Filtering a column of a table, it works fine. Please tell me how to search a joined column. In the following screenshot Manager is a joined column. Manager is alias for parties.name_manager. It's same for both the parent and child view. I am using Kartik Grid.
Here is my index.php for the parent
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use backend\modules\managerproductsalesmonthly\models\ProductsalesdetailsSearch;
/* #var $this yii\web\View */
/* #var $searchModel backend\modules\managerproductsalesmonthly\models\ProductsalesSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Productsales';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="productsales-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<!-- <p>
<?= Html::a('Create Productsales', ['create'], ['class' => 'btn btn-success']) ?>
</p> -->
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'export' => false,
'columns' => [
[
'class' => 'kartik\grid\ExpandRowColumn',
'value' => function($model, $key, $index, $column){
return GridView::ROW_COLLAPSED;
},
'detail' => function($model, $key, $index, $column){
$searchModel = new ProductsalesdetailsSearch();
$searchModel-> productname = $model->productname;
//$searchModel-> total = $model->total;
$searchModel-> manager = $model->manager;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return Yii::$app->controller->renderPartial('_productsales', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
},
],
//['class' => 'yii\grid\SerialColumn'],
// 'id',
// 'productsales_ebillid',
// 'year',
// 'console',
// 'billno:ntext',
[
'attribute' => 'manager',
'value' => 'productsalesPartyname.name_manager'
],
//'billdate',
// 'productsales_partyname',
// 'itemid',
'productname',
// 'batchno',
// 'expdate',
// 'mrp',
// 'rate',
// 'productiondate',
// 'prodqty',
// 'qty',
// 'free',
'total',
// 'discount',
//['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
I've used this guide earlier
http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/
Hope it helps