I have a gridview . It displays the departments available in a college.
When I click the row it populate the modal and Its shows the lecturer available for the selected department in kartik gridview .
In that I am using the kartik/grid/CheckboxColumn.
But when I click the Checkbox and get the selected rows through javacript, It doesn't return primary key associated with the record.
If I execute the gridview without modal , then it works fine
$this->registerJs("
$('#lect-logout').click(function() {
var key = $('#w0-container').yiiGridView('getSelectedRows');
alert(key);
$.post(
'?r=lec-logout/logout',
{
id: $('#w0').yiiGridView('getSelectedRows'),
},
function (data) {
alert("ok");
}
);
});
");
How to use that checkbox with the modal. Even I click select all option in checkbox. It doesn't select all the rows.
Controller Code
public function actionIndex()
{
$searchModel = new CollegeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider]);
}
public function actionLecture()
{
$model = new Accounts();
if ($model->load(Yii::$app->request->post())) {
return $this->redirect(['index']);
}
else{
$searchModel = new LectureSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->renderAjax('lecture', ['searchModel' => $searchModel,'dataProvider' => $dataProvider]);
}
}
View CODE
index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'rowOptions' => function($model, $key, $index, $grid) {
return ['id' => $model['account_id'], 'onclick' => 'getrow(this.id)'];
},
'columns' => [
'displayname',
],
]); ?>
<?php Modal::begin([
'id' => 'show-agents-modal',
'size' => 'modal-lg',
'header' => '<h4 class="modal-title">View</h4>',
]);
Modal::end(); ?>
Lecture.php
<div class="pull-right">
<?= Html::Button('Logout',['class'=>'btn btn-primary','id'=>'lect- logout']); ?>
</div>
<br>
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
'first_name,
['class' => 'kartik\grid\CheckboxColumn'],
],
]); ?>
If you want to use yii\grid\CheckboxColumn then try this :
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => function($model, $key, $index, $column) {
return ['value' => $model->your_id];
},
],
.
.
])?>
Related
This is my grid :
I made a query and created a dataprovider to view in a gridview, and now I want to view each row in a particular view. How do I get all line data to send when clicking preview?
on my controller
$model = new Aviso();
if ($model->load(Yii::$app->request->post())) {
$seg = $model->seguradora;
$seguradora = SeguradoraSearch::getNomeSeg($seg);
$query = new Query;
$query->select(['apolice_idapolice','nome','email', 'contacto','premio','data_final','situacao'])
->from('seguro')
->innerJoin('cliente', 'cliente_idcliente = idcliente')
->where(['between','data_final' ,$model->data_inicio,$model->data_final])
->andWhere(['situacao'=> "Pendente"])
->andWhere(['seguradora_idseguradora'=>$seg]);
$dataAviso = new ActiveDataProvider([
'query' => $query,
]);
return $this->render('index',[
'dataProvider' => $dataAviso,'segName'=>$seguradora,
]);
}
return $this->render('create', [
'model' => $model,
]);
}
On My index
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['attribute'=>'nome',
'label'=> 'Cliente',
],
['attribute'=>'email',
'label'=> 'E-mail',
],
['attribute'=>'apolice_idapolice',
'label'=> 'Apolice',
],
'contacto',
['attribute'=>'premio',
'format' => ['decimal', 2],
'label'=> 'Valor (Mts)',
],
'data_final',
['attribute'=>'situacao',
'label'=> 'Situação',
],
['class' => 'yii\grid\ActionColumn', 'template' => '{view}','header' => 'visualizar' ],
],
]); ?>
<?php Pjax::end(); ?>
I wamt to click on the icon visualizar and render on particular view.
You could configure the ActionColumn in proper way using template and urlCreator
assuming $model->id is you target id for the view
['class' => 'yii\grid\ActionColumn',
'template' => '{view}',
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'view') {
return \yii\helpers\Url::to(['your-controller/your-action', 'id' => $model->id]);
}
}
],
I have default forms which were generated by crud. I need to update message column.
My View site/index.php
<div class="notifications-events-index">
<?= Html::encode($this->title) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => false,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'date_at',
'type',
'event_id',
[
'attribute' => 'Message',
'filter' => true,
'format' => 'raw',
'value' => function ($model) {
$form = ActiveForm::begin([
'action' => Yii::$app->urlManager->createUrl(['site/update', 'id' => $model->id])
]);
return $this->render('_msg', [
'model' => $model,
'form' => $form,
]);
},
]
],
]); ?>
<?php ActiveForm::end(); ?>
My updateAction in SiteController
public function actionUpdate($id)
{
$model = $this->findModel($id);
$dataProvider = new ActiveDataProvider([
'query' => NotificationsEvents::find()->orderBy('date_at'),
]);
if ($model->load(Yii::$app->request->post())) {
$model->save(false);
return $this->redirect(['index']);
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
findModel is working. When I save my updating values they are not updating. Any ideas?
Possible Reason to not updating the records:
Check validation , there may be a chance some validation is applying.
Check you attribute available in safe in your model .
Debug Your POST data. There may be a chance your post data is not posted .
If you still not able to solve it please post you model as well .
I have a relation between User and Thesis and my dataProvider just displays user attributes and not thesis'ones in the Gridview. Is there a better way to print join attributes than: ['attribute'] => ['table.attribute']?
model:
public function search($params)
{
$query = Request::find()->joinWith('user')->joinWith('thesis')->where(['thesis.staff'=> Yii::$app->user->identity->id]);
$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;
}
view:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
//'id',
'title',
['attribute' => 'thesis',
'value' => 'thesis.title'],
//'company',
'description:ntext',
'duration',
['attribute' => 'user'
'value' => 'user.id'],
//'requirements',
//'course',
'n_person',
'ref_person',
'is_visible:boolean',
//'created_at',
//'staff',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
controller:
public function actionIndex()
{
$searchModel = new SearchRequest();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
You need to add the relation getters on your model.
On your Thesis model, you need to add something like
public function getUser0 () {
return $this->hasOne(\your\user\model\location\User::className(), ['id' => 'user']);
}
Having this on your model will populate via lazy-load the user relation when you call Thesis::user0, in your case, something like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
/// ---- other attributes
['attribute' => 'user0.name'],
/// ---- other attributes
],
]); ?>
Is better to add your code after $this->load($params);
My example is:
.
.
.
$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;
}
$query->joinWith('user');
$query->joinWith('thesis');
$query->andFilterWhere(['thesis.staff'=> Yii::$app->user->identity->id]);
.
.
.
I want to use ArrayDataProvider with the following code of siteController. I wrote the following code but it doesn't work.
Here is my actionIndex :
public function actionIndex()
{
$query = new \yii\db\Query;
$query->select('*')->from('business_main_categories');
$query->createCommand();
$dataProviders = [];
foreach ($query as $category) {
$dataProviders[] = new ArrayDataProvider([
'allModels' => $category,
'sort' => false,
'pagination' => false,
]);
}
return $this->render('index', [
'dataProvider' => $dataProviders,
]);
}
And want it to iterate in gridView. So, I wrote the following code (I don't know whether it's correct or not) :
Here is my index.php :
<?php
$dataProviders[] = 'dataProvider';
foreach ($dataProviders as $dataProvider) {
echo GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
[
'attribute' => 'bmc_image',
'format' => 'html',
'label' => '',
'value' => function ($data) {
return Html::img($data['bmc_image'],
['width' => '210px', 'height' => '190px']);
},
],
]
]);
}
?>
Controller
public function actionIndex()
{
$query = new \yii\db\Query;
$dataProvider = new ArrayDataProvider([
'allModels' =>$query->from('business_main_categories')->all(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);
}
Index
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'bmc_image',
'format' => 'html',
'value' => function ($data) {
return Html::img($data['bmc_image'],['width' => '210px', 'height' => '190px']);
},
],
],
]); ?>
I solved my problem without using gridview. As follows -
My SiteController -
public function actionIndex()
{
$searchModel = new BusinessMainCategoriesSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = $dataProvider->getTotalCount(); //-1 : disable
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
using this code I get all records in dataProvider from my db.
(Note that, I'm using ActiveDataProvider in my 'BusinessMainCategoriesSearch' model)
And, my index.php is -
<?php
$m = $dataProvider->getModels();
foreach ($m as $dp) {
echo "<img src = '".$dp['bmc_image']."' />";
echo '<center><font color = "white">'.$dp['bmc_name'].'<font/></center>';
}
?>
It worked great for me & it's a easiest way to do so.
I have 3 tables and i have made relation to What table by using Field table. i want to show name row from What table in Gridview.but it shows me row of data seperated by comma. i want each data in different column. like sql query result with repeated field.
this is my tbon.php model:
public function getWhat()
{
return $this->hasMany(What::className(), ['idw' => 'idw'])
->viaTable('Field', ['id' => 'id']);
}
public function getField()
{
return $this->hasMany(Field::className(), ['id' => 'id']);
}
and in TbonSearch.php i have added these codes:
public $what;
public $field;
and
[['field','what'],'safe']
and in search method, i have added:
$query = Tbon::find()
->joinWith(['field'])
->joinWith(['what']);
and for sorting:
$dataProvider->sort->attributes['what'] = [
'asc' => ['what.name' => SORT_ASC],
'desc' => ['what.name' => SORT_DESC],
];
and add search filter:
->andFilterWhere(['like', 'what.name', $this->what]);
in index i have added this code and here is the problem, i think:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'label'=>'Name',
'attribute' => 'what',
'value' => function ($data) {
$str = '';
foreach($data->what as $name) {
$str .= $name->name.',';
}
return $str;
},
],
data is like this: a,b,c,d for field of name! but i want ID and a then in next row ID and b and etc.
any help will be appreciated!
I dont know your code and I dont get the meaning, but I can answer in general.
A GridView is used to view Data in a Grid. A row in a GridView represents a dataset and presenting data in the form of a table.
foreach($data->what as $name) {
$str .= $name->name.',';
}
I assume you want to display the Name attribute from the relation what. You can simply achieve this with the tablename.columnname syntax.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'label'=>'Name',
'attribute' => 'what.name',
],
If you want to display the ID column additionally:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
[
'label'=>'Name',
'attribute' => 'what',
'value' => function ($data) {
$str = '';
foreach($data->what as $name) {
$str .= ' ';
$str .= $name->id.'';
$str .= $name->name.',';
}
return $str;
},
],
To be more precise (in Terms of your Problem). We have a datamodel with a junction table like the following simple book database.
Example:
If you want to display the names of the authors on the standard CRUD generated index Gridview, you can do something like this:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'book_name',
[
'label'=>'Author(s)',
'value' => function ($dataProvider) {
$str = '';
foreach($dataProvider->authors as $name) {
$str .= ' ';
$str .= $name->id.' ';
$str .= $name->author_name.',';
}
return $str;
},
],
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
with the result:
In addition, you can edit the Detail View to display such an information in an extra Gridview. The result can look like this.
To achieve this you have to:
add a data provider to your controller and pass the provider to the view
add a gridview widget in your view and connect the data provider
add a method to your model which crawls the data
view.php aka the view
use yii\grid\GridView;
// other code
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
[
'attribute' => 'author.author_name',
'header' => 'Author(s)',
],
],
]); ?>
BookController.php aka the controller
public function actionView($id)
{
$dataProvider = Book::getAllAuthors($id);
return $this->render('view', [
'model' => $this->findModel($id),
'dataProvider' => $dataProvider,
]);
}
Book.php aka the model
use \yii\data\ActiveDataProvider;
// other code
public static function getAllAuthors($id) {
$query = BookAuthor::find()->where(['book_id' => $id]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}