Object of class yii\db\ActiveQuery could not be converted to string - yii2

I'm trying to print data with the help of kartik mPDF. The detailview part is printing without any issue. But I need to print some lines along with the detailview. Now I need to pass data from the model to the view to be printed. I'm trying to do that but not so sure. Currently I'm getting error -
Object of class yii\db\ActiveQuery could not be converted to string
I may be wrong in my approach. But please tell me what correction needs to be done. This is the same question as - How to pass data from model to a view in yii2
Code of Controller Action -
public function actionPrintsalarystatement($id) {
//Yii::app()->params['period'] = $period;
//$s_period = $this->originalperiod;
$period = Salary::find()->select(['s_period'])->where(['s_id' => $id])->asArray();
//$period = Yii::$app->request->post('period');
//$this->period = Salary::find()->select(['s_period'])->where(['s_id' => $id]);
//$period = ArrayHelper::map(Salary::find($id)->select(['s_period'])->asArray()->all(), 's_period', 'period'),
//$model = Salary::find()->where(['s_period' => $period]);
$model = $this->findModel($id);
$searchModel = new SalarySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$data = Salary::findOne($id);
$content = $this->renderPartial('_printSalarystatement', [
'model' => $model,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'data'=> $data,
'period' => $period,
]);
$pdf = new Pdf([
'mode'=> Pdf::MODE_UTF8,
'format'=> Pdf::FORMAT_A4,
'destination'=> Pdf::DEST_BROWSER,
//'destination' => Pdf::DEST_DOWNLOAD,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Print Payslip'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['Private and Confidential'],
'SetFooter'=>['This Payslip is computer generated.'],
],
'content' => $content,
]);
return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
}
Updated view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\web\View;
/* #var $this yii\web\View */
/* #var $model frontend\modules\salary\models\Salary */
//#var $model yii\base\Model
//#var $totaldays any
//$this->title = $model->s_id;
//$this->period = $model->s_period;
$this->params['breadcrumbs'][] = ['label' => 'Salaries', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="salary-view">
<h1><strong><p class="text-center">My Company</p></strong></h1>
<p class="text-center">Pay Slip for the month of <?php $model['s_period'];?> </p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
's_id',
's_date',
's_period',
's_empid',
's_empname',
's_workingdays',
's_leave',
's_holiday',
's_wageperday',
's_totalwage',
's_ovthour',
],
]) ?>
</div>
What I'm trying to do -
Currently I'm getting

Comment the $period object you are creating in controller as follows:
public function actionPrintsalarystatement($id) {
//Yii::app()->params['period'] = $period;
//$s_period = $this->originalperiod;
//$period = Salary::find()->select(['s_period'])->where(['s_id' => $id])->asArray(); <=== Comment this line
//$period = Yii::$app->request->post('period');
//$this->period = Salary::find()->select(['s_period'])->where(['s_id' => $id]);
//$period = ArrayHelper::map(Salary::find($id)->select(['s_period'])->asArray()->all(), 's_period', 'period'),
//$model = Salary::find()->where(['s_period' => $period]);
$model = $this->findModel($id);
$searchModel = new SalarySearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$data = Salary::findOne($id);
$content = $this->renderPartial('_printSalarystatement', [
'model' => $model,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'data'=> $data,
//'period' => $period, <=== Comment this as well
]);
$pdf = new Pdf([
'mode'=> Pdf::MODE_UTF8,
'format'=> Pdf::FORMAT_A4,
'destination'=> Pdf::DEST_BROWSER,
//'destination' => Pdf::DEST_DOWNLOAD,
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Print Payslip'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['Private and Confidential'],
'SetFooter'=>['This Payslip is computer generated.'],
],
'content' => $content,
]);
return $pdf->render();
//return $this->render('_printSalarystatement', ['s_period' => $s_period]);
}
And in your view do the following:
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use yii\web\View;
/* #var $this yii\web\View */
/* #var $model frontend\modules\salary\models\Salary */
//#var $model yii\base\Model
//#var $totaldays any
//$this->title = $model->s_id;
//$this->period = $model->s_period;
$this->params['breadcrumbs'][] = ['label' => 'Salaries', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="salary-view">
<h1><strong><p class="text-center">My Company</p></strong></h1>
<p class="text-center">Pay Slip for the month of <?php echo $model['s_period'];?> </p>
<?php
//Add these lines to see what you get in your $Model object
echo '<pre>'; print_r($model); echo '</pre>'; ?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
's_id',
's_date',
's_period',
's_empid',
's_empname',
's_workingdays',
's_leave',
's_holiday',
's_wageperday',
's_totalwage',
's_ovthour',
],
]) ?>

Related

Why does it give an error "missing required parameters: id"?

I understand that the error occurred due to the confusion of variables, although these are my assumptions .. The fact is that this error occurred in the update and in the view: update and view. I have already tried everything .. Please poke your nose where I went wrong?
My controller in which I pass two actions view and update:
public function actionView($id)
{
return $this->render('view', [
'faq' => $this->findModel($id),
]);
}
public function actionUpdate($id)
{
$faq = FaqLang::findOne($id);
$faqLang = Faq::findOne($faq->faq_id);
if ($faq->load(Yii::$app->request->post()) && $faqLang->load(Yii::$app->request->post()) && Model::validateMultiple([$faq, $faqLang]))
{
$faqLang->save(false);
$faq->save(false);
return $this->redirect(['view', 'id' => $faq->id]);
}
return $this->render('update', [
'faq' => $faq,
'faqLang' => $faqLang,
]);
}
protected function findModel($id)
{
if (($faq = FaqLang::findOne($id)) !== null) {
return $faq;
}
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
}
view.php in which I am trying to display data using DetailView
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $faqLang app\modules\admin\models\Faq */
/* #var $faq app\modules\admin\models\FaqLang */
//$this->title = $faq->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="faq-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $faq->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $faq->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'faq' => $faq,
'attributes' => [
'id',
['attribute' => 'name', 'value' => 'faqLang.name'],
['attribute' => 'body', 'value' => 'faqLang.body:ntext'],
'put_date',
[
'attribute' => 'hide',
'format' => 'html',
'value' => function($model) {
if($model->hide == 'show')
return 'Нет';
else
return 'Да';
}
],
],
]) ?>
update.php through which the records are updated
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $faqLang app\modules\admin\models\Faq */
/* #var $faq app\modules\admin\models\FaqLang */
$this->title = Yii::t('app', 'Update Faq: ' . $faq->id, [
'nameAttribute' => '' . $faq->id,
]);
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Faqs'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $faq->id, 'url' => ['view', 'id' => $faq->id]];
$this->params['breadcrumbs'][] = Yii::t('app', 'Update');
?>
<div class="faq-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'faq' => $faq,
'faqLang' => $faqLang,
]) ?>
</div>
And 2 related Faq and FaqLang models
Faq.php
public function getFaqLang()
{
return $this->hasMany(FaqLang::className(), ['faq_id' => 'id']);
}
FaqLang.php
public function getFaq()
{
return $this->hasOne(Faq::className(), ['id' => 'faq_id']);
}
You may be seeing this error because the request path/query string you're using to run your controller actions does not include the $id parameter.
If you specify a method parameter in a controller action, that parameter must be defined in your routes, and passed in the request
Your action methods are as follows:
public function actionView($id)
{
....
}
Which expects a route like
'/view/<id:\d+>' => 'admin/faqs/view'
and
public function actionUpdate($id)
{
...
}
Which expects a route like
'/update/<id:\d+>' => 'admin/faqs/update'
So for example, for the request /view/123 , the value 123 is passed as the value of $id into the actionView($id) method.
If you have a route set up like
'/view' => 'admin/faqs/view'
There's no id parameter defined, and the controller will throw the error missing required parameters: id

Yii2 - Two models in one form - Values are not saved in the second model

I have a model called Patientinformation.php and a model called AlternativeInformation.php. I would like to use the two models in the patientinformation_form.php
Patientinformation model:
- id (PK)
- patient_id
- patient_initials
- collection_site
- cancer
- study (FK to study model)
AlternativeInformation model:
- alternative_id (PK)
- patients_patient_id (FK to id of the Patientinformation model)
- alternative_study (FK to study model)
- alternative_patient_id
I have updated the Patientinformation controller as well as the create.php file and the _form.php file.
If I enter values in the Patientinformation form.php, I am redirected to the Patientinformation view site. The values of the Patientinformation model (id, patient_id, patient_initials, collection_site, cancer and study) are saved in the database. However, the values of the AlternativeInformation model (alternative_study and alternative_patient_id) are not saved in the database.
This is the PatientinformationController.php file:
<?php
namespace app\controllers;
use Yii;
use app\models\Patientinformation;
use app\models\AlternativeInformation;
use app\models\PatientinformationSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* Creates a new Patientinformation model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Patientinformation();
$modelAlternative = new AlternativeInformation();
if ($model->load(Yii::$app->request->post()) && $modelAlternative->load(Yii::$app->request->post())){
$model->save();
$modelAlternative->patients_patient_id = $model->id;
$modelAlternative->save();
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('create', [
'model' => $model,
'modelAlternative' => $modelAlternative,
]);
}
This is the create.php file:
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model app\models\Patientinformation */
/* #var $modelAlternative app\models\AlternativeInformation */
$this->title = 'Add patient';
$this->params['breadcrumbs'][] = ['label' => 'Patients', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="patientinformation-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'modelAlternative' => $modelAlternative,
]) ?>
</div>
And this is the _form.php file:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\CollectionSiteInformation;
use app\models\AlternativeInformation;
use app\models\StudyInformation;
use app\models\CancerInformation;
use unclead\multipleinput\MultipleInput;
use kartik\select2\Select2;
/* #var $this yii\web\View */
/* #var $model app\models\Patientinformation */
/* #var $modelAlternative app\models\AlternativeInformation */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="patientinformation-form">
<?php $form = ActiveForm::begin(); ?>
<p>
Please note that all fields marked with an asterisk (<font color="red">*</font>) are required.
</p>
<?= $form->field($model, 'study')->widget(Select2::classname(), [
'data' => ArrayHelper::map(StudyInformation::find()->all(),'id','study'),
'language' => 'en',
'options' => ['placeholder' => 'Please select a study'],
]);
?>
<?= $form->field($model, 'patient_id')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'patient_initials')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'collection_site')->widget(Select2::classname(), [
'data' => ArrayHelper::map(CollectionSiteInformation::find()->all(),'id','collection_site'),
'language' => 'en',
'options' => ['placeholder' => 'Please select a collection site'],
]);
?>
<?= $form->field($model, 'cancer')->widget(Select2::classname(), [
'data' => ArrayHelper::map(CancerInformation::find()->all(),'id','cancer'),
'language' => 'en',
'options' => ['placeholder' => 'Please select a cancer type'],
]);
?>
<?= $form->field($modelAlternative,'alternative_study')->widget(MultipleInput::class,[
'max' => 6,
'allowEmptyList' => false,
'enableGuessTitle' => true,
'columns' => [
[
'name' => 'alternative_study',
'type' => 'dropDownList',
'title' => 'Alternative Study',
'items' => ArrayHelper::map(studyInformation::find()->asArray()->all (),'id','study'),
'options' => ['prompt' => 'Please select an alternative study if applicable'],
],
]
])
->label(false);
?>
<?= $form->field($modelAlternative,'alternative_patient_id')->widget(MultipleInput::class,[
'max' => 6,
'allowEmptyList' => false,
'enableGuessTitle' => true,
'columns' => [
[
'name' => 'alternative_patient_id',
'title' => 'Alternative patient ID',
'options' => ['prompt' => 'Please select an alternative study if applicable'],
],
]
])
->label(false);
?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
If I don`t use unclead\multipleinput\MultipleInput in my _form.php, all the values of AlternativeInformation model (alternative_study and alternative_patient_id) are saved into the model/database.
So I assume that I don`t pass any items to the MultipleInput widget.
This is the AlternativeInformation model file:
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['patients_patient_id', 'alternative_study'], 'required'],
[['patients_patient_id', 'alternative_study'], 'integer'],
[['alternative_patient_id'], 'string', 'max' => 265],
[['patients_patient_id'], 'exist', 'skipOnError' => true, 'targetClass' => PatientInformation::className(), 'targetAttribute' => ['patients_patient_id' => 'id']],
[['alternative_study'], 'exist', 'skipOnError' => true, 'targetClass' => StudyInformation::className(), 'targetAttribute' => ['alternative_study' => 'id']],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'alternative_id' => 'Alternative ID',
'patients_patient_id' => 'Patients Patient ID',
'alternative_study' => 'Alternative Study',
'alternative_patient_id' => 'Alternative Patient ID',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPatientsPatient()
{
return $this->hasOne(PatientInformation::className(), ['id' => 'patients_patient_id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getAlternativeStudy()
{
return $this->hasOne(StudyInformation::className(), ['id' => 'alternative_study']);
}
}
Does anyone have any suggestions how this issue can be solved? How will be the values of "alternative_study" and "alternative_patient_id" saved into the AlternativeInformation model if using the MultipleInput widget?
I really need the option in the form to enter no, one or several alternative studies as well as alternative patient ids.
I really appreciate any help how I can solve this issue.
Thanks :)
You are probably getting some validation errors that you can't see because you are redirecting to the view action even if the AlternativeInformation model has validation errors.
The first step towards finding a solution would be making sure that, if AlternativeInformation doesn't save you show the form again, that way you will see the validation errors.
Update your controller code to this:
public function actionCreate()
{
$model = new Patientinformation();
$modelAlternative = new AlternativeInformation();
if ($model->load(Yii::$app->request->post())
&& $modelAlternative->load(Yii::$app->request->post())
&& $model->save()) {
$modelAlternative->patients_patient_id = $model->id;
if ($modelAlternative->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
'modelAlternative' => $modelAlternative,
]);
}
That should help you find the problem, it will also give your users information about any future errors that may happen.
The validation problem may be on alternative_patient_id, it seems that you are not passing any items to the MultipleInput widget.
Update your controller with the following code.
public function actionCreate()
{
$model = new Patientinformation();
$modelAlternative = new AlternativeInformation();
if ($model->load(Yii::$app->request->post()) && $modelAlternative->load(Yii::$app->request->post())){
if($model->save()){
$modelAlternative->patients_patient_id = $model->id;
$modelAlternative->save();
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
'modelAlternative' => $modelAlternative,
]);
}

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.

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