yii2: Gridview selected rows processing issue - ajax post data missing

Within my yii2 application, I am looking to group machines into specific machine groups. Due to the large number of machines, users must select them via a checkbox column in a kartik-gridview, which offers sorting and filtering capabilities that a standard multiselect form field lacks.

The challenge arises when attempting to process the selected rows of the grid. The only solution I have found involves using Javascript, as outlined in this forum post: http://www.yiiframework.com/forum/index.php/topic/53777-gridview-get-selected-colum/

To achieve this, I've incorporated the following code snippet within a button:

<?= Html::button(yii::t('app', 'Save'), ['class' => 'btn btn-primary', 
        'onclick' => "var keys = $('#w0.grid-view').yiiGridView('getSelectedRows');"
                    . "$.ajax({"
                    . "type: 'POST',"
                    . "url: 'http://localhost:8080/eddb1/frontend/web/index.php?r=machine-group/test',"
                    . "dataType: 'json',"
                    . "data: {keylist: keys}});"]) ?>

As highlighted, I had to resort to using $.ajax rather than $.post, as the latter resulted in a 404 not found error due to issues with the URL.

However, I'm encountering an issue where the ajax POST request is consistently empty. Here's the controller code snippet designed to echo the post-request data:

public function actionTest()
{
        echo var_dump(Yii::$app->request->post());
        die();
}

I even attempted using:

echo var_dump($_POST);

with identical results. What could be causing this problem? Is there a way to process the selected rows without relying on Javascript? I experimented with embedding the gridview within ActiveForm tags and using a standard submitButton, but no post-request was triggered.

If anyone can provide assistance, I've been grappling with this for 2 days now...thank you in advance!

PS.: below is the gridview code snippet:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel'=>$searchModel,
    'columns' => [
        ['class' => 'kartik\grid\CheckboxColumn'],
        'company_name',
        'identifier',
        'licenceplate',
        'serial_number',
        'type_name',
        'class_name',
        'manufacturer',
        'model_name',
        'variant_name',
    ],
    'persistResize' => true,
    'showPageSummary' => false,
    'pjax' => true,
    'panel' => [
       'before' => ''
    ],
    'toolbar' => [
        '{export}',
        '{toggleData}'
    ]
]);  
?>

Answer №1

Resolved: The issue was caused by the fact that "getSelectedRows" was returning the primary keys of a table-based model. However, my dataprovider and searchmodel for the gridview were based on a MySQL-View without primary keys, resulting in the function always returning an empty keys-array.

I had to utilize the primaryKey-Function to define a PK in my view-model, regenerate my searchmodel with GII, and now everything is functioning smoothly (remember to declare your PK as an array, even if it consists of a single attribute).

Answer №2

It appears that the method you are using to access the data is incorrect. You might want to consider using a different approach, such as:

var selectedKeys = $(this).parents('.gridview').yiiGridView('getSelectedRows');

One benefit of this method is that it does not rely on a variable identifier. The w0 portion is generated by a counter within the Widget functionality and can vary if other widgets are present before the GridView. Therefore, I recommend avoiding referencing the ID in this scenario.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

There are two different ways to set a hyperlink in HTML. One method is by using the href attribute, where you provide the URL inside the quotation marks. The other

While browsing, I stumbled upon this interesting piece of JavaScript code: onClick="self.location.href='http://stackoverflow.com/'" I incorporated this code into my website, and it seems to have the same effect as using the href attribute. Sin ...

Set $scope.model childs to an empty string or a null value

While working on a form, I am using a $http request to send the information through Angular in the following manner: $http({ method:"POST", url: "controllers/servicerequest.php", data: { servicerequest: $scope. ...

Tips for avoiding deleting content within a span element when using contenteditable

I am working on an HTML 5 editor that utilizes the contenteditable tag. Inside this tag, I have a span. The issue arises when all text is removed as the span also gets removed. I want to prevent the removal of the span, how can I achieve this? Here is a s ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Display the uploaded images from uploadify on the webpage

I am currently working on a PHP website that utilizes uploadify for users to upload portfolio images. While I have successfully implemented uploadify, I am now exploring the most effective way to display these uploaded images on the webpage without requir ...

Tips for altering the contents of a state in react by toggling items in and out

Here's a challenge I'm facing: I need to display products based on the checkboxes toggles. If none of the checkboxes are toggled, the product array should be empty. If the men's checkbox is toggled, only men-related products should be shown, ...

Using `this` within an object declaration

I am encountering an issue with the following code snippet: const myObj = { reply(text: string, options?: Bot.SendMessageOptions) { return bot.sendMessage(msg.chat.id, text, { reply_to_message_id: msg.message_id, ...options }) ...

What could be the reason for my typeahead.js not showing the dropdown menu during an ajax request?

I am currently experiencing an issue with the typeahead.js autocomplete in my Laravel application when using AJAX as the data source. The suggestion menu does not display when using AJAX, but it works perfectly fine when the data is retrieved from a div co ...

Step-by-step guide on utilizing the GitHub API to automatically generate a pull request with modified files

What is the process for creating a PR on Github using their API? For example, if I have a package.json file as a string and I want to modify it, I would need to parse it, make the changes, and then how do I ensure these changes are reflected locally afte ...

Troubleshooting the Create Order Issue: Integrating PayPal Checkout with Smart Payment Buttons using React and Redux

Every time I attempt to process a payment, I encounter a 422 error: Unprocessable entity. The issue arises when I try to dynamically capture the purchased item details received from the redux store. I tried following this example (duplicate): PayPal Check ...

Showing a database table in an HTML format using JavaScript

I am currently working on displaying a database table in HTML. I have written a PHP code snippet which retrieves the table data and formats it into an HTML table without any errors: function viewPlane() { if(!$this->DBLogin()) { $ ...

Combine two events in jQuery using the AND operator

Can I create a condition where two events are bound by an AND logic operator, requiring both to be active in order for a function to be called? Let's say you have something like this: foobar.bind("foo AND bar", barfunc); function barfunc(e) { al ...

Challenges of performance in EmberJS and Rails 4 API

My EmberJS application is connected to a Rails 4 REST API. While the application is generally working fine, it has started to slow down due to the nature of the queries being made. Currently, the API response looks like this: "projects": [{ "id": 1, ...

Change the destination of an iFrame upon user click

Is it possible to redirect an iFrame to a different HTML page when clicked by the user? I have an iFrame that is essentially an HTML page. When I click on the iFrame, I want it to take me to another HTML page. This is my code: h1 { ...

The occurrences of Swiper events fail to be activated

I am in the process of developing a gallery website that utilizes the Swiper JQuery plugin for slideshows and isotope for grid layout. Each individual item within the gallery has its own slider and corresponding isotope element. The Swiper gallery is in ...

What is the best way to verify the presence of # in a URL?

Every now and then, due to caching issues, I find myself adding a # to my URL, like so: http://www.example.com/#lang=3201954253 My goal is to find and remove the #lang from the URL if it is present. ...

Retrieving input field values in JS/Ajax without needing to refresh the page or click a button

Currently, I have set up a JavaScript function that submits data without refreshing the page or requiring a button click. The input field is located within tab #2 and triggers the JS function when the user stops typing. However, the issue arises when the ...

The navigation links will remain visible even when the unordered list is set to 0% opacity

I've been working on creating a side navigation menu using HTML, CSS, and Javascript. I successfully implemented the function to toggle open and close the navigation, but upon adding a background image, I noticed that the links still appear even when ...

Transmitting boolean values from a Python API request

Is it possible that the error in my script is due to the boolean value I am trying to send in an API put call using Requests in Python? Here is how my script looks: import requests data = { 'name': 'John', 'lastname': ...