I have one search form with a field and a button. On the button click I want to search 2 searchmodel - sellitembtdtSearch and puritembtdtSearch. The result will be shown in one view. I can display the view without any problem. The problem is when I'm searching only one searchmodel is getting searched. Please let me know how can I search both the searchModel at the sametime.
First I land on index2.php page where the form is.
'action' => ['/stock/sellitem/printproductledger3',],
'method' => 'get',
<?= $form->field($model, 'productname')->textInput(['maxlength' => true,]) ?>
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
actionIndex2.php
public function actionIndex2()
{
$searchModel1 = new SellitemsbdtSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->queryParams);
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render('_formbtdt', [
'model' => $searchModel2,
//'searchModel1' => $searchModel2,
]);
}
public function actionPrintproductledger3() {
$searchModel1 = new SellitemsbdtSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->get());
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->get());
//$productname = yii::$app->request->get('productname');
//$prodesc = yii::$app->request->get('prodesc');
$content = $this->renderPartial('_printproductledgerbtdt', [
//'productname' => $productname,
'searchModel1' => $searchModel1,
'dataProvider1' => $dataProvider1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
//'prodesc' => $prodesc,
]);
return $this->render('_printproductledgerbtdt', [
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
This code only searchs puritemdtdtSearch. I want to search puritembtdtSearch and sellitembtdtSearch at the same time. Thanks.
The issue is you are using searchModel2 in your form so you are just getting the result of searchModel2. And not getting the result of searchModel1.
What you can do is send searchModel1 to your _search file.
<?php echo $this->render('_search', ['model1' => $searchModel1, 'model2' => $searchModel2]); ?>
Now in your form use a hidden input.
<?php echo $form->field($model1, 'productName')->textInput(['id' => 'model1']); ?>
<?php echo $form->field($model2, 'prodcutName')->hiddenInput(array('id' => 'model2')); ?>
Now its that we have two model fields we need to populate the hidden field, this can be done using jquery.
<?php $this->registerJs('
//add the .search class name for your search button
jQuery("body").on("click", ".search", function() {
alert("Hello");
var a = $("#model1").val();
$("#model2").attr("value", a);
});
');?>
Try this..tested completely and works fine!!
Related
Friends,
I have an INDEX page with 3 GRIDVIEW components (model Keys, model Products, model Indicators). And on that same page I have a search form with a dropdownlist (company).
I need to: When you select for example company 02 the 3 GRIDVIEW are filtered only company records 02.
_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\date\DatePicker;
?>
<div class="ideas-search">
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'form-inline',
],
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'pa')->dropdownList([..])?>
...
index.php
<?php echo $this->render('_search', ['model' => $searchBase]); ?>
<?php Pjax::begin(['id' => '1']) ?>
<?= GridView::widget([
'id' => 'grid1',
'dataProvider' => $dataProviderKey,
'columns' => [
...
],
]); ?>
<?php Pjax::end() ?>
<?php Pjax::begin(['id' => '2']) ?>
<?= GridView::widget([
'id' => 'grid2',
'dataProvider' => $dataProviderProduct,
'columns' => [
...
],
]); ?>
<?php Pjax::end() ?>
<?= GridView::widget([
'dataProvider' => $dataProviderIndicators,
'summary' => false,
'columns' => [
...
],
]); ?>
== UPDATE==
BaseController
public function actionIndex()
{
$searchBase = new BaseSearch();
$searchBase->pa = 0;
$searchBase->data = date("Y-m-d");
$dataProviderBase = $searchBase->search(Yii::$app->request->queryParams);
$searchMobilizadores = new MobilizadoresSearch();
$dataProviderMobilizadores = $searchMobilizadores->search(Yii::$app->request->queryParams);
$searchIndicadores = new IndicadoresSearch();
$dataProviderIndicadores = $searchIndicadores->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchBase' => $searchBase,
'dataProviderBase' => $dataProviderBase,
'searchMobilizadores' => $searchMobilizadores,
'dataProviderMobilizadores' => $dataProviderMobilizadores,
'searchIndicadores' => $searchIndicadores,
'dataProviderIndicadores' => $dataProviderIndicadores,
]);
}
dont forget define filterModel in your Gridview Widget
view file
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
1st Approach :
You may use a single model that extend from model that joint all 3 table and create a search model for it. If u insist on separating all 3 table in the view, you may just declare different column for each grid.
a tip to achieve this, you may create a view and use gii tool to generate view file.
the tricky part is that 1 model can only hold one table except you joint. But, by joining table, you may get extra rows that are not necessarily needed for lets say your $dataProviderKey grid.
2nd Approach :
manually check for params from Yii::$app->request->get() add filter for each $dataprovider.
controller file
if(isset($id = Yii::$app->request->get('company_id'))) {
$dataProviderKey->query->andFilterWhere(['company.id' => $id]);
$dataProviderProduct->query->andFilterWhere(['company.id' => $id]);
$dataProviderIndicators->query->andFilterWhere(['company.id' => $id]);
}
== UPDATE ==
to answer your update question, you may assign your base search attributes to the respective attributes from others searchModel like this :
public function actionIndex()
{
$searchBase = new BaseSearch();
$searchBase->pa = 0;
$searchBase->data = date("Y-m-d");
$dataProviderBase = $searchBase->search(Yii::$app->request->queryParams);
$searchMobilizadores = new MobilizadoresSearch();
$searchMobilizadores->company = $searchBase->company; -->add this
$dataProviderMobilizadores = $searchMobilizadores->search(Yii::$app->request->queryParams);
$searchIndicadores = new IndicadoresSearch();
$searchIndicadores->company = $searchBase->company; -->add this
$dataProviderIndicadores = $searchIndicadores->search(Yii::$app->request->queryParams);
I got an error message, when i want to load back saved elements on update form.
Controller
$contentCategory = ContentCategory::find()
->where(['content_id' => $id])->all();
View
<?= $form->field($contentCategory, 'category_id')
->dropdownList(ArrayHelper::map(Category::find()->all(),'id','title'),
['prompt'=>'Select Category', 'multiple' => 'multiple']
)->label('Add categories'); ?>
The error message.
Call to a member function isAttributeRequired() on array
If i change the all() method to one() it's works but select only one element (of course).
Update:
#scaisEdge I'm using a content_category junction table to insert relations contents with categories.
content_id category_id
1 2
1 3
Model
public function rules()
{
return [
[['content_id', 'category_id'], 'integer'],
[['category_id'], 'exist', 'skipOnError' => true, 'targetClass' => Category::className(), 'targetAttribute' => ['category_id' => 'id']],
[['content_id'], 'exist', 'skipOnError' => true, 'targetClass' => Content::className(), 'targetAttribute' => ['content_id' => 'id']],
];
}
The trouble in that you use $contentCategory array of founded models as form field model.
I think you should just change $contentCategory variable from your view on your certain model like $model = ContentCategory::findOne($id);
#Csaba Faragó
$arr = array();
$colorarr=array();
foreach ($detmodel as $key => $detailm){
//$detailm;
$id = $detailm['productid'];
$sid = $detailm['sizeid'];
$sidex= explode(",",$sid);
$i = 0;
foreach($sidex as $size_id)
{
$val = $sidex[$i];
$val = (int)$val;
array_push($arr, $val);
$i++;
}
<?php $sizelist = ArrayHelper::map(Size::find()->all(),'id','size');
// $idd = '4';
?>
<?php
$detailm->sizeid = $arr;
// print_r($detailm->sizeid);
?>
<?= $form->field($detailm, 'sizeid')->widget(Select2::classname(), [
'data' => $sizelist,
'language' => 'de',
'options' => ['placeholder' => 'Select sizes ...','multiple' => true],
'pluginOptions' => [
'tags' => true,
'tokenSeparators' => [',', ' '],
'maximumInputLength' => 10
],
]);
?>
do all this in view page
I have found a solution here. He is perfectly solve my issue.
I have a form field and a button in a form. The button should get the data from the form field and pass the value as parameter. Please tell me how can I get the data from the form field and pass the value.
form field -
<?= $form->field($model, 'productname')->textInput(['maxlength' => true]) ?>
button
<?= Html::a('Search', ['/stock/sellitem/printproductledger3', 'productname' => '8904187001305'], ['class'=>'btn btn-primary']) ; ?>
The above example work fine because the value is already given here 'productname' => '8904187001305'
What I need to do is get the value '8904187001305' from the form field. Please help.
actionIndex
public function actionIndex2()
{
$searchModel = new SellitemsbdtSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('_formbtdt', [
'model' => $searchModel,
]);
}
This index leads to _formdtbt
'action' => ['/stock/sellitem/printproductledger3',],
<?= $form->field($model, 'productname')->textInput(['maxlength' => true,]) ?>
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
Controller action printproductledger3
public function actionPrintproductledger3() {
$searchModel1 = new SellitemsbdtSearch();
$dataProvider1 = $searchModel1->search(Yii::$app->request->get());
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(Yii::$app->request->get());
return $this->render('_printproductledgerbtdt', [
'dataProvider1' => $dataProvider1,
'searchModel1' => $searchModel1,
'searchModel2' => $searchModel2,
'dataProvider2' => $dataProvider2,
]);
}
Well, I think I've pointed to wrong issue. The issue is model sellitemsbdtSearch is getting filtered but puritemsbdtSearch is not getting filtered.
Search Model sellitemsbdtSearch
public function search($params)
{
//$query = Sellitem::find();
$query = Sellitem::find()
->joinWith(['siSs'])
->select(['sellsum.ss_date as date','si_iupc','si_idesc', 'concat("By sales to Tax Invoice ", sellsum.ss_invno) as particular', 'si_qty as sellqty','(si_qty * si_rate) as value'])
->orDerBy([
'sellsum.ss_date'=>SORT_DESC,
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 10000000000,],
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
if($this->productname){
$query->andFilterWhere(['si_iupc'=> $this->productname]);
return $dataProvider;
}
}
Search Model puritemsbdtSearch
public function search($params)
{
$query = Puritem::find()
->joinWith(['psi'])
->select(['pursum.ps_date as date','pi_upc','pi_desc', 'concat("By purchase to Tax Invoice ", pursum.ps_invno) as particular', 'pi_qty as buyqty','(pi_qty * pi_rate) as value'])
->orDerBy([
'pursum.ps_date'=>SORT_DESC,
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => ['pageSize' => 10000000000,],
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
if($this->productname){
$query->andFilterWhere(['pi_upc'=> $this->productname]);
return $dataProvider;
}
}
You could use this way for sending the value of the model to your action
<?php $form = ActiveForm::begin([
'action' => ['your_action'],
'method' => 'your_method ', /// get or post
]); ?>
<?= $form->field($model, 'productname')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
once submit you cant get the value in the normale yii2 way
you can see this for more .. http://www.yiiframework.com/doc-2.0/guide-input-forms.html
for the second Model that don't have the same realetd model and filed as the first you should use
// in $get try retrive the content of $get (in this case i related your yourModel1)
$get = Yii::$app->request->get(['yourModel1'])
// and the use the value for searching in your model2 with the proper value
// obviously you should adatp the name in this sample with the proper ones
$searchModel2 = new PuritemsbdtSearch();
$dataProvider2 = $searchModel2->search(['YourModelSearch2Name'=>['yourAttributeYouNeed'=>$get['productname']]]);
It there any way to make 'data-confirm' => Please enter the number' not just confirm but some like JS prompt and get imputed values to sent it to controller?
<?php \yii\widgets\Pjax::begin(['id' => 'pjax-orders_table','clientOptions' => ['method' => 'POST'], 'enablePushState'=>false]) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'id'=>'orders_table',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
///some columns
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}{some}',
'buttons' => [
'some' => function ($url,$model,$key) {
if($model->status=='not confirm')
{
return Html::a('<span class="glyphicon glyphicon-trash"</span>',['my/some', 'id' => $model->id],[
'title' => Yii::t('yii', 'Delete'),
'data-confirm' => Please enter the number',
'data-method' => 'post',
]);
}
},
],
],
],
]); ?>
<?php \yii\widgets\Pjax::end() ?>
In controller
public actionSome()
{ $dataProvider = new ActiveDataProvider();
$dataProvider->query = Orders::find()->all();
return $this->render('some',['dataProvider'=>$dataProvider]);
}
instead of Html::a() use Html::button()where button id = some_item_id and then write this JS code
$('.buttons_class').click(function(){
var selection;
do{
selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10);
}
while(isNaN(selection));
if(!isNaN(selection))
{
$.post("some",{id:45,prompt_value:selection}, function(response)
{
console.log(response);
$.pjax.reload({container:'#pjax-orders_table'});
});
}
})
I'm trying to use fill my listView using an ArrayDataProvider. However the dataProvider consists of Arrays, not objects. I ran into this problem because the category in the model is an id, where I need the name corresponding to that id from another table. Hence I created an Array where the id is the corresponding name.
private function getDataProvider()
{
return new ArrayDataProvider([
'allModels'=>$this->getFaqs(), // returns array of faqs
'sort'=>[
'attributes'=>['id','category','question','answer']],
'pagination'=>[
'pageSize'=>10,
],
]);
}
Here is my ListView widget
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => function($dataProvider, $key, $index, $widget)
{
return Html::a($dataProvider->question,
Url::toRoute(['faq/view', 'id' => $dataProvider->primaryKey]));
}
]);
It works, I use it like this
$dataProvider = new ArrayDataProvider([
'allModels' => [['name' => '0am - 6am'], ['name' => '6am - 9pm'], ['name' => '9am - 12pm'], ['name' => '12pm - 3pm'], ['name' => '3pm - 6pm']],
]);
<?= ListView::widget([
'dataProvider' => $dataProvider,
'layout' => "{items}",
'itemOptions' => ['class' => 'item', 'style' => 'margin-bottom: 5px;'],
'itemView' => function ($model, $key, $index, $widget) use ($transportRun) {
//return print_r($model, true);
return Html::a(Html::encode($model['name']), ['delivery/index', 'DeliverySearch' => ['transport_run' => $transportRun, 'timeslot' => $key]], ['class' => 'btn btn-lg btn-primary btn-block']);
},
]) ?>
ListView and GridView can use any class that implements yii\data\DataProviderInterface. You can take a look here http://www.yiiframework.com/doc-2.0/yii-data-dataproviderinterface.html to see who implements it, so you can use any of those classes on both ListView and GridView.
You should also be able to do a
'allModels'=>$this->faqs, // returns array of faqs