Yii2 Pjax and GridView - refresh is not working properly - yii

I am using the Pjax and GridView, and trying to make it work properly after the status of the item is changed. Currently, after the action is over, and server sends back the result, the whole GridView will be replaced with the text (response from the controller).
The Pjax code:
<?php
Pjax::begin(['id' => 'product-manage']);
echo GridView::widget([
'dataProvider' => $productsProvider,
'filterModel' => $filterModel,
'filterPosition' => 'header',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
....
['class' => 'yii\grid\ActionColumn',
'header' => 'Actions',
'buttons' => [
....
'toggle-publish' => function ($url, $model) {
$html = $model->published ? '<span class="glyphicon glyphicon-remove"></span>' : '<span class="glyphicon glyphicon-ok"></span>';
return Html::a($html, $url, [
'title' => $model->published ? 'Unpublish' : 'Publish',
'data-pjax' => 'product-manage',
'data' => [
'confirm' => $model->published ? 'Are you sure you want to unpublish ' . $model->inci . ' ?' : 'Are you sure you want to publish ' . $model->inci . ' ?',
'method' => 'post',
],
]);
},
],
'template' => '<span class="block text-center">{view}</span>
<span class="block text-center">{update}</span>
<span class="block text-center">{toggle-default-product}</span>
<span class="block text-center">{toggle-publish}</span>'
],
],
]);
Pjax::end();
?>
Controller:
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
$response->statusCode = 200;
$response->data = Yii::$app->controller->renderPartial('/partials/_alerts', [
'message' => $message,
'type' => 'success'
]);
return $response;
What am I doing wrong here?

Related

Yii2 data-* attributes not rendered using GridView Column

How do add data-id in below function:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'contentOptions' => ['class' => "text-center"],
'attribute' => 'scale',
"format"=>"Html",
"value"=>function($model){
return '<div class="myClass" data-id="'.$model->id.'">'.$model->scale.'</div>';
}
],
],
]);
Here is data-id attribute which is not shown in the browser:
"value"=>function($model){
return '<div class="myClass" data-id="'.$model->id.'">'.$model->scale.'</div>';
}
You need to change the format for the column to raw for the column
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'contentOptions' => ['class' => "text-center"],
'attribute' => 'scale',
"format"=>"raw",
"value"=>function($model){
return '<div class="myClass" data-id="'.$model->id.'">'.$model->scale.'</div>';
}
],
],
]);
EDIT
Apart from returning the html like,
return '<div class="myClass" data-id="'.$model->id.'">'.$model->scale.'</div>';
You can use the yii\helpers\Html::tag($name,$content,$options[]) to create a div tag see below.
return Html::tag('div',$model->scale,['class'=>'myClass','data'=>['id'=>$model->id]]);

How add one more button to yii2-widget-fileinput?

I want more button in yii2-fileinput-widget.
My current code is like this:
$allPics = \common\models\Picture::getPictures($album->id);
$images = [];
$imagesOptions = [];
if($allPics){
foreach ($allPics as $pic){
$key = $pic->id;
$url = Url::to(['set-pic-status', 'id'=>$key, 'pid'=>$model->id, 'do'=>'remove']);
$images[] = Yii::$app->urlManagerFront->createAbsoluteUrl(['image/index', 'id'=>$pic->id, 'width'=>300, 'height'=>300]);
$imagesOptions[] = ['caption' => $pic->name, 'size' => $pic->size , 'url'=>$url, 'key'=>$key];
}
}
echo FileInput::widget([
'name' => 'pic',
'language'=>'fa',
'options'=>[
'multiple'=>true
],
'pluginOptions' => [
'uploadUrl' => Url::to(['pic-upload', 'id'=>$model->id]),
'initialPreview'=>$images,
'initialPreviewAsData'=>true,
'initialCaption'=>"تصاویر محصول",
'initialPreviewConfig' => $imagesOptions,
'overwriteInitial'=>false,
'maxFileSize'=>2800,
]
]);
And result of top code is:
Now I need add one more button near remove button to send some data to server and set selected picture as cover or change status of picture in db.
How can I do that?
try this:
$initialPreview = [];
$initialPreviewConfig = [];
foreach($model->images as $image){
$initialPreview[] = Html::img($image->imagePath,['width' =>200]);
$initialPreviewConfig[] = [
'url' => \yii\helpers\Url::to(['/admin/portfolio/portfolio/image-delete']),
'key' => $image->ID,
];
}
?>
<br>
<div class="row">
<div class="col-md-12">
<?php
echo FileInput::widget([
'name' => 'ProductImages[]',
'options'=>['accept'=>'image/*','multiple' => true],
'pluginOptions' => [
'otherActionButtons' => '<button class="set-main" type="button" {dataKey} ><i class="glyphicon glyphicon-star"></i></button>',
'overwriteInitial'=>false,
'maxFileSize'=>2800,
'fileActionSettings' => [
'fileActionSettings' => [
'showZoom' => false,
'showDelete' => true,
],
],
'browseClass' => 'btn btn-success',
'uploadClass' => 'btn btn-info',
'removeClass' => 'btn btn-danger',
'showRemove' => false,
'showUpload' => false,
'initialPreview' => $initialPreview,
'initialPreviewConfig' => $initialPreviewConfig,
],
]);
$this->registerJs("
$('.set-main').on('click',function(){
$.get('" . \yii\helpers\Url::to(['/admin/portfolio/portfolio/set-main-image/']) . "', {id:$(this).attr('data-key')});
});
");
?>
</div></div>
<div>
'otherActionButtons' => '...';

How to display Image in gridview yii2

I'm new to yii, i want to display an image in gridview table, anyhelp will be appreciated, below is my code.
view....
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
//['class' => 'yii\grid\SerialColumn'],
'product_id',
'name',
'descr',
'price',
//'image',
[
'attribute'=>'image',
'label'=>'Image',
'format'=>'html',
'value' => function ($data) {
$url = \Yii::getAlias('#backend/web/').$data['image'];
return Html::img($url, ['alt'=>'myImage','width'=>'70','height'=>'50']);
}
],
'views',
['class' => 'yii\grid\ActionColumn'],
],
'tableOptions' =>['class' => 'table table-striped table-bordered'],
I'm using dataProvider and below is my controller
public function actionIndex()
{
$searchModel = new ProductSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
//$models = $dataProvider->getModels();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
//'models' => $models,
]);
}
The above code is not working fine no image display only the img alt shown
Any help on how to get this work, thanks
Here is the solution :
[
'attribute' => 'Icon',
'format' => 'html',
'label' => 'Icon',
'value' => function ($data) {
return Html::img(Yii::$app->request->BaseUrl.'/uploads/path/' . $data['Icon'],
['width' => '60px']);
},
],
Check you image path,
You can use
Yii::$app->request->baseUrl
If your index file is on root directory
$url =Yii::$app->request->baseUrl.'/'.$data['image'];
Specify 'format' to 'raw' for image column and $data should be and object, so 'image' field is accessible with $data->image.
[
'attribute'=>'image',
'label'=>'Image',
'format'=>'raw',
'value' => function ($data) {
$url = \Yii::getAlias('#backend/web/').$data->image;
return Html::img($url, ['alt'=>'myImage','width'=>'70','height'=>'50']);
}
],

click yii2 gridview linkpager's page no, jump error

the gridview if on right of the page,left is some menus,when click on page no 2,it dose not only refresh the gridview,but all page including left part are lost——a totally new page come out!help~
there is the debugging Screenshot:
my action is
public function actionList()
{
$model = new Loan();
$dataProvider = new ActiveDataProvider([
'query' => $model->find(),
'pagination' => [
'pagesize' => '1',
],
]);
return $this->renderPartial('list', ['model' => $model, 'dataProvider' => $dataProvider]);
}
my view is:
<?php
use yii\grid\GridView;
use yii\grid\SerialColumn;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\LinkPager;
?>
<?=GridView::widget([
'dataProvider' => $dataProvider,
'layout'=> '{items}{pager}',
'columns' => [
['attribute' =>'loan_type','label'=>'借款类型','options' => ['width' => '80']],
['attribute' =>'amount','label'=>'金额','options' => ['width' => '80']],
['attribute' =>'rate','label'=>'还款利率','options' => ['width' => '80']],
['attribute' =>'fee','label'=>'手续费','options' => ['width' => '80']],
['attribute' =>'status','label'=>'状态','options' => ['width' => '80'] ],
['attribute' =>'comment','label'=>'审核意见','options' => ['width' => '80']],
['attribute' => 'created_at','value' =>function($model){return date('Y-m-d',strtotime($model->created_at));},'label'=>'申请时间','options' => ['width' => '150']],
[
'class' => 'yii\grid\ActionColumn',
'header' => '操作',
'template' => '{audit}',
'buttons' => [
'audit' => function ($url,$model) {
return Html::a('<span id="xxxx" class="glyphicon glyphicon-user"></span>','#',['title'=>'审核',
'onclick'=>"
$.ajax({
type: 'GET',
dataType: 'text',
url: 'http://182.92.4.87:8000/index.php?r=loan/pj', //目标地址
error: function (XMLHttpRequest, textStatus, errorThrown) {alert(XMLHttpRequest.status + ':' + XMLHttpRequest.statusText); },
success: function (page)
{
$('.ucRight').html(page);
}
});
return false;",
]);},
],
'urlCreator' => function ($action, $model, $key, $index) {
return Yii::$app->getUrlManager()->createUrl(['loan/list','id' => $model->status]);
},
'headerOptions' => ['width' => '80'],
],
],
]);
?>
The reason for your problem is that you haven't prevented the html link from directing to a new page, so your user is clicking on the link, which then loads a new page with the contents returned by the server; in this case a page of information with no layout applied. You need to add event.preventDefault() before the ajax call to stop this behaviour.
However, as #arogachev said, if you simply want to use pagination without a page refresh, then just use pjax. That is what pjax is designed for,

Yii CGridView custom footer

I am using CGridView to show data in grid format, but i am not able to create a custom footer,
the code that i am using,
<?php
$this->widget('zii.widgets.grid.CGridView',
array('dataProvider' => $dataProvider,
'columns' => array(
array(
'name' => 'created_date',
'header' => 'Created',
),
array(
'name' => 'access_date',
'header' => 'Accessed',
),
array(
'name' => 'referenceCode',
'header' => 'Ref Code',
),
array(
'name' => 'designation',
'header' => 'Designation',
),
array(
'name' => 'company',
'header' => 'Company',
),
array(
'name' => 'recommended_actions',
'header' => 'Recommended Action',
'type' => 'html',
'value' => function($jobBoard) {
return CHtml::link($recAction[0]['display_text'], Yii::app()->createUrl($actionUrl, $params));
}
),
array(
'class' => 'CDataColumn',
'header' => 'List of Actions',
'type' => 'html',
'value' => function($jobBoard){
echo '<div class="action-joborder">
<ul class="moveto-joborder">
<li>Action <img height="6" width="7" alt="" src="images/bg_action.gif">
<ul>';
echo '<li>'.CHtml::link($actionArray['display_text'], Yii::app()->createUrl($actionUrl, $params)).'</li>';
echo '</ul>
</li>
</ul>
</div>';
},
'name' => 'actions',
),
)));
?>
the above code gives me footer with pagination only, i want to place a some Button element to give the grid some control.
the grid should look like,
is there any way i can make custom element at the footer.
You can extend framework/zii/widgets/grid/CGridView.php and use it in your code. extend the following method to change footer
public function renderTableFooter()
{
$hasFilter=$this->filter!==null && $this->filterPosition===self::FILTER_POS_FOOTER;
$hasFooter=$this->getHasFooter();
if($hasFilter || $hasFooter)
{
echo "<tfoot>\n";
if($hasFooter)
{
echo "<tr>\n";
foreach($this->columns as $column)
$column->renderFooterCell();
echo "</tr>\n";
}
if($hasFilter)
$this->renderFilter();
echo "</tfoot>\n";
}
}
protected/components/GridView.php
Yii::import('zii.widgets.grid.CGridView');
class GridView extends CGridView
{
/**
* Renders the table footer.
*/
public function renderTableFooter()
{
$hasFilter=$this->filter!==null && $this->filterPosition===self::FILTER_POS_FOOTER;
$hasFooter=$this->getHasFooter();
if($hasFilter || $hasFooter)
{
echo "<tfoot>\n";
if($hasFooter)
{
echo "<tr>\n";
foreach($this->columns as $column){
if($column->footer!='')
$column->footer=eval("return " . $column->footer.";");
$column->renderFooterCell();
}
echo "</tr>\n";
}
if($hasFilter)
$this->renderFilter();
echo "</tfoot>\n";
}
}
public function sumTotal($attribute){
$data=$this->dataProvider->getData();
$sum=0;
foreach($data as $index => $value ){
if(isset($data[$index]->{$attribute}))
$sum+=$data[$index]->{$attribute};
}
return $sum;
}
}
views/{controllers}/{action}.php
$this->widget('GridView',
array('dataProvider' => $dataProvider,
'columns' => array(
array(
'name' => 'created_date',
'header' => 'Created',
),
array(
'name' => 'access_date',
'header' => 'Accessed',
),
array(
'name' => 'referenceCode',
'header' => 'Ref Code',
),
array(
'name' => 'designation',
'header' => 'Designation',
),
array(
'name' => 'company',
'header' => 'Company',
),
array(
'name' => 'recommended_actions',
'header' => 'Recommended Action',
'type' => 'html',
'value' => function($jobBoard) {
return CHtml::link($recAction[0]['display_text'], Yii::app()->createUrl($actionUrl, $params));
}
'footer'=> 'number_format($this->sumTotal("recommended_actions"))',
),
array(
'class' => 'CDataColumn',
'header' => 'List of Actions',
'type' => 'html',
'value' => function($jobBoard){
echo '<div class="action-joborder">
<ul class="moveto-joborder">
<li>Action <img height="6" width="7" alt="" src="images/bg_action.gif">
<ul>';
echo '<li>'.CHtml::link($actionArray['display_text'], Yii::app()->createUrl($actionUrl, $params)).'</li>';
echo '</ul>
</li>
</ul>
</div>';
},
'name' => 'actions',
),
)));