jQuery(function ($) { $('.js-batch-delete').click(function(e) { e.preventDefault(); var…
- User
jQuery(function () { ('.js-batch-delete').click(function(e) {
e.preventDefault(); var rowIds = $('#w0').yiiGridView('getSelectedRows'); if (rowIds.length === 0) { alert('Please select at least one item to delete.'); return; } if (!confirm('Are you sure you want to delete the selected items?')) { return; } $.ajax({ type: 'POST', url: '" . Url::toRoute(['session-user/multiple-delete']) . "', data: {row_id: rowIds}, success: function() { $.pjax.reload({container: '#w0-pjax'}); // Reload the grid via PJAX }, error: function() { alert('An error occurred while attempting to delete the items. Please try again.'); } }); });});
need this as vanilla js
- Assistant
Certainly! Here's your jQuery code rewritten into vanilla JavaScript. This version uses equivalent methods to handle clicks, AJAX calls with
fetch, confirmation dialogs, and DOM element selection.document.addEventListener('DOMContentLoaded', function() { var batchDeleteBtn = document.querySelector('.js-batch-delete'); if (!batchDeleteBtn) return; batchDeleteBtn.addEventListener('click', function(e) { e.preventDefault(); // Get selected rows from yiiGridView // This example assumes selected checkboxes have 'input[name="selection[]"]:checked' inside #w0 var checkboxes = document.querySelectorAll('#w0 input[name="selection[]"]:checked'); var rowIds = Array.from(checkboxes).map(function(chk) { return chk.value; }); if (rowIds.length === 0) { alert('Please select at least one item to delete.'); return; } if (!confirm('Are you sure you want to delete the selected items?')) { return; } // The URL, replace with your yii Url helper output or write directly as a string var url = "<?= \yii\helpers\Url::toRoute(['session-user/multiple-delete']) ?>"; fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', // suggested to mimic AJAX 'X-CSRF-Token': (document.querySelector('meta[name="csrf-token"]') || {}).content || '' }, body: new URLSearchParams({row_id: rowIds}) }) .then(function(response) { if (!response.ok) { throw new Error('Network response was not ok'); } return response.text(); }) .then(function() { // Reload the grid via PJAX equivalent // Pure vanilla JS PJAX reload - you have to implement reloading or trigger pjax in your environment var pjaxContainer = document.querySelector('#w0-pjax'); if (pjaxContainer) { // If yii Pjax is used, you can trigger reload via yii Pjax js api: // But since this is vanilla, we'll try to reload the container via fetch // Or you can force full page reload: // location.reload(); // Or you can trigger a custom event or call your grid reload method accordingly // For demonstration, let's trigger a reload by dispatching an event: var event = new CustomEvent('pjax:reload'); pjaxContainer.dispatchEvent(event); } else { // Fallback reload: location.reload(); } }) .catch(function() { alert('An error occurred while attempting to delete the items. Please try again.'); }); }); });Explanation:
- Replaced jQuery click with
addEventListener('click', ...). - Selected checked checkboxes inside
#w0with thename="selection[]"attribute to get selected IDs. - Confirm and alert dialogs remain the same.
- The AJAX call uses
fetchwithPOSTand URL encoded body params byURLSearchParams. - Added
X-CSRF-Tokenassuming Yii2 CSRF meta tag exists. - On success, it attempts to reload the PJAX container or falls back to page reload. You'll need to adjust this based on how you want to reload your grid.
- Make sure your server handles the POST request correctly.
Let me know if you want me to help with the PJAX reload logic specific to your scenario!
- Replaced jQuery click with
- User
'buttons' => [ 'delete' => function (model, key) { return (layout->isAdmin) ? Html::a('', $url, [ 'title' => \Yii::t('app', 'Delete'), 'aria-label' => 'Delete', 'data-confirm' => 'Are you sure you want to delete this item?', 'data-method' => 'post', 'data-toggle' => 'tooltip', ]) : ''; },
PHP Warning – yii\base\ErrorException Undefined variable $layout
- Assistant
The error **"Undefined variable layout
is not defined or passed into the scope where you are trying to access it—in this case, inside the anonymous function for the'delete'` button within your GridView configuration.Why does this happen?
Anonymous functions like the one you use in
'delete' => function ($url, $model, $key) {...}have their own local scope. Variables from the outer scope are not automatically available inside this function.How to fix it?
You need to pass the variable into the anonymous function using the
usekeyword.For example, if
$layoutis defined in the file/view where you also define your GridView widget:<?= GridView::widget([ 'columns' => [ [ 'class' => 'yii\grid\ActionColumn', 'buttons' => [ 'delete' => function ($url, $model, $key) use ($layout) { return ($layout->isAdmin) ? Html::a('<i class="bi bi-trash3-fill icon-size"></i>', $url, [ 'title' => \Yii::t('app', 'Delete'), 'aria-label' => 'Delete', 'data-confirm' => 'Are you sure you want to delete this item?', 'data-method' => 'post', 'data-toggle' => 'tooltip', ]) : ''; }, ], ], ], ]); ?>Explanation
use ($layout)imports the variable$layoutfrom the parent scope into the anonymous function, making it accessible inside.- Without this,
$layoutis undefined inside the function, causing the error you see.
Additional notes
- Make sure
$layoutis defined before you callGridView::widget()in your view or controller. For example:
$layout = Yii::$app->user->identity; // or however you get the object with isAdmin property- If
$layoutis a component or a model, adjust accordingly.
Summary
- Declare
$layoutbefore the GridView statement. - Pass it into your anonymous function via
use ($layout). - Then you can access
$layout->isAdminsafely inside your button rendering function.
If you want, I can help you rewrite your full GridView code snippet with this fixed.
- User
- Assistant
Thanks for sharing your context! Since you have already a
$layoutvariable defined before your GridView call...$layout = \Yii::$app->layoutManager;You must import
$layoutinside any anonymous function you use in GridView button definitions (or any callback) like this:<?= GridView::widget([ 'columns' => [ [ 'class' => ActionColumn::class, 'buttons' => [ 'delete' => function ($url, $model, $key) use ($layout) { return ($layout->isAdmin) ? Html::a('<i class="bi bi-trash3-fill icon-size"></i>', $url, [ 'title' => \Yii::t('app', 'Delete'), 'aria-label' => 'Delete', 'data-confirm' => 'Are you sure you want to delete this item?', 'data-method' => 'post', 'data-toggle' => 'tooltip', ]) : ''; }, ], ], // other columns ... ], ]); ?>Why?
- The anonymous function you pass to
'delete'creates a closure. - Variables defined outside are not available inside unless explicitly imported with
use(). $layoutholds yourlayoutManagercomponent, so import it to access$layout->isAdmin.
If
$layoutis not an object or missingisAdminMake sure:
$layoutis set by the time this code runs.$layout->isAdminis valid, i.e., that property/method exists and returns what you expect.
Summary
Your full setup should look like:
<?php declare(strict_types=1); use yii\grid\ActionColumn; use yii\grid\GridView; use yii\helpers\Html; $layout = \Yii::$app->layoutManager; echo GridView::widget([ 'columns' => [ [ 'class' => ActionColumn::class, 'buttons' => [ 'delete' => function ($url, $model, $key) use ($layout) { if ($layout->isAdmin) { return Html::a('<i class="bi bi-trash3-fill icon-size"></i>', $url, [ 'title' => \Yii::t('app', 'Delete'), 'aria-label' => 'Delete', 'data-confirm' => 'Are you sure you want to delete this item?', 'data-method' => 'post', 'data-toggle' => 'tooltip', ]); } return ''; }, ], ], ], ]);
If you want me to check the entire GridView config or integration with
$layout, feel free to share that code! - The anonymous function you pass to