Yii2 GridView action column doesn't send post parameter - yii2

I am trying to send simple post param through Html:a() element in my GridView. But the id doesn't reach the action. This is what I tried (seen in documentation):
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}',
'buttons' => [
'update' => function($url, $model){
return Html::a('<span class="glyphicon glyphicon-edit"></span>', ['c-update', 'id' => $model->id], [
'data' => [
'method' => 'post',
],
]);
}
]
],
The method is post and in controller verbs the action c-update is set to receiving only post requests. var_dump($_POST) in the action is empty array.

Your ID is in $_GET. Second argument of Html::a() method is for generating URL, it does not define data for POST request. So you're sending empty (without data) POST request to /my-controller/c-update?id=123 URL.
You can get this ID easily in your action:
public function actionCUpdate($id) {
// ...
}
If you really want to send ID as POST data you should do something like:
Html::a('<span class="glyphicon glyphicon-edit"></span>', ['c-update'], [
'data' => [
'method' => 'post',
'params' => [
'id' => $model->id,
],
],
]);
But you should probably not do this. It is easy to lose context whe you're sending ID of modified record as POST data (since for every record URL will be the same). Using GET params to identify requested resources is perfectly fine.

Related

Yii2 Pagination + PrettyURL Cannot Find site/index

I have pagination setup in site/index, with pretty url working. But my site/index is hidden by either the rewrite engine of Apache, or by UrlManager. In any case, my index page address is simply "X.COM' and pagination wishes to redirect a page change to "X.COM/index?PAGINATIONQUERY", so it always returns a 404.
Example Pagination Request (Returns 404):
x.com/index?page=2&per-page=12
Here is my UrlManager
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
// '<alias:\w+>' => 'site/<alias>',
'<action:\w+>' => 'site/<action>',
],
],
How would I either remove the 'index' portion from pagination requests, or allow myself to see /index in Url again?
Thank you!
Edit:
This is my Index action
public function actionIndex()
{
$query = Shout::find()->orderBy(['id' => SORT_DESC]);
$countQuery = $query->count();
$pagination = new Pagination(['totalCount' => $countQuery, 'pageSize' => 12]);
$shouts = $query->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'shouts' => $shouts,
'pagination' => $pagination,
]);
}
Use Yii2 Gii for Generating Crud Modules with Inbuilt Pagination & Searching.
Yii2 Gii - https://www.yiiframework.com/doc/guide/2.0/en/start-gii
Make Sure Pjax enable when create crud with Gii.

In Yii2 Kartik Select2 widget how to make an ajax call on select event?

In select2 widget of yii2, how can we make an ajax call from the widget to a function in our controller:
Scenario is I need to create a custom ID for a table the id depends upon the two dropdown value and on select event of the select2 drop down I need to fetch the record and construct the ID and put the value of the newly created id in the form filed.
I just have problem in making an ajax call from the select2 dropdown widget
Try following:
You can use select2:select event to make ajax call.
echo $form->field($model, 'state_1')->widget(Select2::classname(), [
'data' => $data,
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
"select2:select" => "function() { // function to make ajax call here }",
]
]);
'pluginEvents' => [
'change' => 'function() {
var selectedIds = $(this).val();
$.pjax.reload({container: "#testing", data:{tags:selectedIds}});
}'

Pushstate in pjax only when redirecting

In one of my pages I have a link that is handled by pjax. Basically the user clicks an item, this item becomes "checked" (and saved in the DB).
I have disabled pushState for these requests, because it makes no sense, user effectively stays in the same page, so it's counter-intuitive to change the url.
However, there is a case when this pjax request results in redirect to login page (when the user is not logged in). And this is when I really need pushState to work, and it doesn't because I disabled it in the first place.
Would it be possible to configure pjax in such a way that normal responses work without pushState, but redirect responses (done with X-Pjax-Url header) do perform pushState?
There's no way to do it using current functionality. I've added two more options to pjax and my PR has been accepted to yii2 branch of pjax. So, without further ado:
https://github.com/yiisoft/jquery-pjax
//pushRedirect - Whether to pushState the URL for redirects. Defaults to false.
//replaceRedirect - Whether to replaceState the URL for redirects. Defaults to true.
// ...
jQuery(document).pjax("#example_selector", {
"push": false,
"replace": false,
"pushRedirect": true,
"replaceRedirect": false
});
Use a linkSelector to specify which links trigger the pjax calls
<?php Pjax::begin([
'enablePushState' => false, // don't change the Browser URL
'linkSelector' => 'pjax-btn', // pjax links that
]); ?>
<?= GridView::widget([
//...
[ // no pjax, normal linl
'label' => 'link with state replace',
'format' => 'raw',
'value' => function ($model, $key, $index, $column) {
return Html::a($model->title, Url::to(['/controllet/action', 'id' => $model->id]));
}
],
[
'class' => 'yii\grid\ActionColumn',
//'class' => 'common\widgets\ActionColumn',
'template' => '{toggle} {view} {update} {delete}',
'buttons' => [
'toggle' => function ($url, $model, $key) {
$options = [
'title' => 'Privacy',
'aria-label' => 'Privacy',
'class' => 'pjax-btn', // no state replacement, load with pjax
];
$icon = Html::tag('span', '', ['class' => 'glyphicon glyphicon-check']);
return Html::a($icon, $url, $options);
},
]
]]) ?>
<?php Pjax::end(); ?>

Send serialize data on kartik file input

I am implementing \kartik\file\FileInput widget.
Here is my code:
<?php
echo FileInput::widget([
'name' => 'dataSiswa',
'options' => [
'multiple' => false
],
'pluginOptions' => [
'uploadUrl' => Url::toRoute('pesertadidikuploadproses'),
'uploadExtraData' => ['folderId' => ""],
'showUpload' => true
],
'pluginEvents' => [
'fileuploaded' => "function(event, data, previewId, index) {
$('#pesan').show();
$('#pesan').html(data.response.pesan);
}"
]
]);
?>
I want the value of uploadExtraData should be get as serialize data form --> $('#formid').serialize();
Like said in this post, you can't direct access to files on a user computer. One technique is to use and iframe to do the submission and that way you won't have to refresh the page.
So use this plugin and just do something as below:
$(function() {
$('#ifoftheform').ajaxForm(function(result) {
alert('the form was successfully processed');
});
});

Yii2 create user friendly URL with parameters

Hi I've to create user friendly URL but when using with parameters it's not working.
Url:
Url::to(['site/index', 'id' => 1]);
url looks like :
localhost/testApplication/frontend/web/index.php/site/index?id=1
/forntend/config/main.php
'urlManager' => [
'class' => 'yii\web\UrlManager',
'enablePrettyUrl' => true,
//'showScriptName' => false,
'rules' => [
],
],
I want a output like
localhost/testApplication/frontend/web/index.php/site/index/id/1
and after that how to access id value in controller.
'rules' => [
'site/index/id/<id:\d+>' => 'site/index'
//'site/index/<id:\d+>' => 'site/index' Better solution
//'<controller>/<action>/<id:\d+>' => '<controller>/<action>' Will be applied for all controllers and actions
],
Routing Doc.
And after in your action :
public function actionIndex($id)
{
...
}
Is really strange, for me using the parameter 'id' always show errors, I needed to change the parameter to 'user_id', but in other parts of the code I could use, really don't know why, but try to rename the parameter.