Multiply of two columns in yii2 - yii2

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.

Related

Searching records for date fails

Following code should search records for date. But whatever I click,main branch in condition will be executed,so I will get outprinting:
choice_date is false
It will be searched for records which are <=department_created_date,but never for records >=department_created_date
Any ideas,how to fix this?
Here is my RadioList
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\widgets\ActiveForm;
$this->title = Yii::t('app', 'Departments');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="departments-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php
$form = ActiveForm::begin();
$model = new backend\models\DepartmentsSearch();
?><?= $form->field($model, 'choice_date')->radioList(array(0 => 'Before', 1 => 'After'))->label('Please, choose Datesearching!'); ?>
<p><?= Html::a(Yii::t('app', 'Create Departments'), ['create'], ['class' => 'btn btn-success']) ?></p>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'branches_branch_id',
'label' => Yii::t('app', 'Branch'),
'value' => function($model) {
if ($model->branches_branch_id) {
return $model->branchesBranch->branch_name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => backend\models\Branches::getBranchList(),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Branch', 'id' => 'grid-Branch-search-rechtsart']
],
'branchesBranch.branch_name',
'department_name',
[
'attribute' => 'companies_company_id',
'label' => Yii::t('app', 'Company'),
'value' => function($model) {
if ($model->companies_company_id) {
return $model->companiesCompany->company_name;
} else {
return NULL;
}
},
'filterType' => GridView::FILTER_SELECT2,
'filter' => backend\models\Companies::getCompanyList(),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Company', 'id' => 'grid-Company-search-rechtsart']
],
'department_created_date',
['class' => 'yii\grid\ActionColumn'],
],
]);
?>
</div>
and here is my searching class:
<?php
namespace backend\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use backend\models\Departments;
class DepartmentsSearch extends Departments {
public $choice_date;
public function rules() {
return [
[['department_id'], 'integer'],
[['choice_date'], 'boolean'],
[['department_name', 'department_created_date', 'department_status', 'companies_company_id', 'branches_branch_id'], 'safe'],
];
}
public function scenarios() {
return Model::scenarios();
}
public function search($params) {
$query = Departments::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate())
return $dataProvider;
/*
Whatever I click in RadioList,property will be 0,so I'll get setFlash->'choice_date is false'
*/
if ($this->choice_date == 0) {
Yii::$app->session->setFlash('If-branch is false', 'choce_date is false');
$query->andFilterWhere(['<=', 'department_created_date', $this->department_created_date]);
} else {
Yii::$app->session->setFlash('if-branch is true', 'choice_date is true');
$query->andFilterWhere(['>=', 'department_created_date', $this->department_created_date]);
}
$query->joinWith('companiesCompany');
$query->joinWith('branchesBranch');
$query->andFilterWhere(['like', 'department_name', $this->department_name])
->andFilterWhere(['like', 'companies.company_name', $this->companies_company_id])
->andFilterWhere(['like', 'branches.branch_name', $this->branches_branch_id])
->andFilterWhere(['like', 'department_status', $this->department_status]);
return $dataProvider;
}
}
Further ideas,how to fix this misery?
P.S.: For Bizley's help, here is an extraction of my controller:
class DepartmentsController extends Controller{
public function actionIndex(){
$searchModel = new DepartmentsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
further methods are irrelevant,here. Why will property of date-record not be rendered in view?
}
Your $model in the view is RadioForm so the form sends this field as RadioForm[choice_date].
But you are expecting choice_date from DepartmentsSearch model and this field is left empty.
Remove the RadioForm model, it's totally unneeded. Use DepartmentsSearch model in the form view.
Update:
Since OP finally told that this is a GridView I can update my answer to suit him.
There is filterSelector property in GridView you can use - you can set there additional jQuery selectors that will be used for filtering.
Here is updated code with comments below:
<?php $form = ActiveForm::begin();
echo $form->field($searchModel /* 1 */, 'choice_date')->radioList([
0 => 'Before', 1 => 'After'
], ['itemOptions' => ['class' => 'choiceRadio' /* 2 */]])->label('Please, choose Datesearching!');
ActiveForm::end(); /* 3 */ ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterSelector' => '.choiceRadio', /* 4 */
// ...
This is the $searchModel I was talking about. You don't need any other model here.
You can set here any CSS class you want, it's for filterSelector.
Don't forget to close form like you did in your original code.
This is the selector for the radio input. Mind the notation - . for CSS class, # for CSS id.

How to send model id to ActiveFrom field

I have a view team/view where I have details for the team (from the model Team).
views/team/view.php:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\grid\GridView;
use yii\data\ActiveDataProvider;
use app\models\Pt;
/* #var $this yii\web\View */
/* #var $model app\models\Team */
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => 'Teams', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="team-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'tournament.name',
'teamindex',
'region.name',
'rank',
],
]) ?>
<?= Html::a('add players to the team', ['pt/create'], ['class'=> 'btn btn-success']) ?>
</div>
Last link is a link button to add players to the team: <?= Html::a('add players to the team', ['pt/create'], ['class'=> 'btn btn-success']) ?>
In views/pt/create I have an ActiveForm with fields: team (dropdown list), player (dropdown list). So, if I want to add a player to the team I should choose the team's name from a looong dropdown list and then choose a player (and some player options..).
Here is views/pt/create.php:
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
/* #var $this yii\web\View */
/* #var $model app\models\Pt */
$this->title = 'Add players to the team';
$this->params['breadcrumbs'][] = ['label' => 'Players in teams', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="pt-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
Here is views/pt/_form.php:
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use app\models\Player;
use yii\helpers\ArrayHelper;
/* #var $this yii\web\View */
/* #var $model app\models\Pt */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="pt-form">
<?php $form = ActiveForm::begin(['id'=>'owner-form']); ?>
<?= $form->field($model, 'team_id')->dropDownList($model->teamList) ?>
<?= $form->field($model, 'player_id')
->dropDownList(ArrayHelper::map(Player::find()->joinWith('category')
->orderBy(['lastname'=>SORT_ASC])->all(), 'id', 'lastname'));
?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Add' : 'Update', ['class' => $model
->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I want like this: when I am on http://localhost/myproject/web/team/100 I click on that button <?= Html::a('add players to the team', ['pt/create'], ['class'=> 'btn btn-success']) ?>
and go to pt/create where in the field team already defined team_id =100 and so I need to input only player.
How can I do that? I know this is simple but I'm still learning.
PS: Models Team and Pt have relations,
models/Team.php
public function getPt()
{
return $this->hasMany(Pt::className(), ['team_id' => 'id']);
}
You should create a proper cation for create the player with the id_team already assigned (or you can modify the original create)
/**
* Creates a new Palyer model assigning the id_team.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreateForTeam(id_team)
{
$model = new Player();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
$model->id_team = $id_team
return $this->render('create', [
'model' => $model,
]);
}
}
Then send the proper id_team
Html::a('add players to the team', ['pt/create-for-teaam', 'id_team'=> $model->team_id],
['class'=> 'btn btn-success']) ?>

Calculate average from kartik gridview(YII2)

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>

Search data by taking input from datepicker in yii2

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

Filtering a joined column in Kartik Grid in Yii2

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