YII2框架下如何获取选中复选框的用户ID并传递至控制器?
在Yii2中实现选中非活跃用户并发送邮件的解决方案
1. 修正前端代码错误
原前端代码存在语法错误,先修正循环逻辑和变量引用,同时补充必要的表单结构:
<!-- 包裹在表单中,确保请求合规 --> <form id="send-reminder-form" method="post"> <!-- Yii2必需的CSRF令牌,防止跨站请求伪造 --> <?= yii\helpers\Html::csrfInput() ?> <ul> <?php foreach($users as $user): ?> <li> <input class="is-selected" type="checkbox" name="user_ids[]" value="<?= $user->id ?>" /> <span><?= $user->name ?></span> </li> <?php endforeach; ?> </ul> <button type="submit" class="btn is-primary">Send Reminder</button> </form>
核心修正点:
- 循环变量避免重名,将数据源变量改为
$users,循环内使用$user - 给复选框设置
name="user_ids[]",让选中的ID自动以数组形式提交 - 强制添加CSRF令牌,这是Yii2 POST请求的必要验证
2. 使用jQuery获取选中ID并异步提交
如果需要无刷新提交,添加以下JS代码:
$(document).ready(function() { $('#send-reminder-form').on('submit', function(e) { e.preventDefault(); // 阻止默认表单跳转 // 收集所有选中的用户ID var selectedIds = []; $('.is-selected:checked').each(function() { selectedIds.push($(this).val()); }); if (selectedIds.length === 0) { alert('请至少选择一个用户'); return; } // AJAX提交到控制器 $.ajax({ url: '<?= yii\helpers\Url::to(['user/send-reminder']) ?>', type: 'POST', data: { user_ids: selectedIds, _csrf: $('input[name="_csrf"]').val() // 传递CSRF令牌 }, success: function(res) { if (res.success) { alert('邮件发送成功'); $('.is-selected').prop('checked', false); // 清除选中状态 } else { alert('发送失败:' + res.message); } }, error: function() { alert('请求出错,请稍后重试'); } }); }); });
3. 控制器处理邮件发送逻辑
在UserController中添加对应的处理方法:
use Yii; use yii\web\Response; use app\models\User; public function actionSendReminder() { Yii::$app->response->format = Response::FORMAT_JSON; if (!Yii::$app->request->isPost) { return ['success' => false, 'message' => '无效请求方式']; } $userIds = Yii::$app->request->post('user_ids', []); if (empty($userIds)) { return ['success' => false, 'message' => '未选择任何用户']; } // 筛选非活跃用户(根据你的业务状态字段调整) $users = User::find() ->where(['id' => $userIds]) ->andWhere(['status' => User::STATUS_INACTIVE]) ->all(); if (empty($users)) { return ['success' => false, 'message' => '选中用户不存在或并非非活跃状态']; } // 批量发送邮件 $successCount = 0; $mailer = Yii::$app->mailer; foreach ($users as $user) { try { $mailer->compose() ->setFrom('your-service@example.com') ->setTo($user->email) ->setSubject('账户激活提醒') ->setTextBody("尊敬的{$user->name},您的账户已处于非活跃状态,请及时登录激活") ->send(); $successCount++; } catch (\Exception $e) { Yii::error("发送邮件给用户ID {$user->id} 失败:{$e->getMessage()}"); } } return [ 'success' => true, 'message' => "成功发送{$successCount}封邮件,失败" . (count($users) - $successCount) . "封" ]; }
注意事项:
- 确保User模型包含
email和status字段,根据实际业务调整状态值 - 提前在
config/web.php中配置好SwiftMailer邮件组件 - 加入错误日志,方便排查发送失败的具体原因
内容的提问来源于stack exchange,提问作者Dr Br And
相关产品推荐
相关产品推荐

