Anonymous
Как передать выбранные значения из представления в контроллер с помощью select2 в Yii2
Сообщение
Anonymous » 18 окт 2024, 06:29
Я использую kartik select2 для подбора чисел.
Контроллер
Код: Выделить всё
public function actionDownload()
{
var_dump($_REQUEST);
die(0);
}
Когда я нажимаю кнопку «Загрузить Excel», я получаю NULL или array(0) { в своем контроллере. Как передать выбранные значения? Их может быть несколько.
Обновленный код
Форма
Контроллер
Код: Выделить всё
public function actionDownload()
{
$postData = Yii::$app->request->post();
$msnArray = $postData['TaskConfig']['msn'];
// Remove any empty values from the array
$msnArrayFilter = array_filter($msnArray);
if (empty($msnArrayFilter)) {
Yii::$app->session->setFlash('error', 'No meters selected.');
return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
}
$dataProvider = new ActiveDataProvider([
'query' => TaskConfig::find()->select(['msn', 'ak', 'ek', 'utility'])->where(['msn' => $msnArrayFilter]),
'pagination' => false,
]);
$models = $dataProvider->getModels();
// Create Excel file
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Set headers
$sheet->setCellValue('A1', 'Msn');
$sheet->setCellValue('B1', 'Ak');
$sheet->setCellValue('C1', 'Ek');
$sheet->setCellValue('D1', 'Utility');
// Fill data
$row = 2;
foreach ($msnArray as $msn)
{
// Assuming TaskConfig::find() returns models with the same attributes as the Excel columns
$model = TaskConfig::find()->where(['msn' => $msn])->one();
if ($model !== null) {
$sheet->setCellValue('A' . $row, $model->msn);
$sheet->setCellValue('B' . $row, $model->ak);
$sheet->setCellValue('C' . $row, $model->ek);
$sheet->setCellValue('D' . $row, $model->utility);
$row++;
}
}
// Save the Excel file content to a temporary file
$microseconds = microtime(true); // Get current timestamp with microseconds
$microseconds = str_replace('.', '', $microseconds); // Remove the dot from microseconds
$filename = 'task_config_' . date('YmdHis') . '_' . $microseconds . '.xlsx';
try {
// Save Excel file to temporary location
$tempFilePath = sys_get_temp_dir() . '/' . $filename;
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($tempFilePath);
// Send the file content to the user for download
Yii::$app->response->sendFile($tempFilePath, $filename)->send();
return;
} catch (\Throwable $e) {
// Handle any exceptions
Yii::error('Error generating Excel file: ' . $e->getMessage());
Yii::$app->session->setFlash('error', 'An error occurred while generating the Excel file.');
return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);
}
}
Любая помощь будет очень признательна
Подробнее здесь:
https://stackoverflow.com/questions/782 ... t2-in-yii2
1729222162
Anonymous
Я использую kartik select2 для подбора чисел. [code] [/code] [b]Контроллер[/b] [code]public function actionDownload() { var_dump($_REQUEST); die(0); } [/code] Когда я нажимаю кнопку «Загрузить Excel», я получаю NULL или array(0) { в своем контроллере. Как передать выбранные значения? Их может быть несколько. [b]Обновленный код[/b] [b]Форма[/b][code] [/code] [b]Контроллер[/b] [code]public function actionDownload() { $postData = Yii::$app->request->post(); $msnArray = $postData['TaskConfig']['msn']; // Remove any empty values from the array $msnArrayFilter = array_filter($msnArray); if (empty($msnArrayFilter)) { Yii::$app->session->setFlash('error', 'No meters selected.'); return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl); } $dataProvider = new ActiveDataProvider([ 'query' => TaskConfig::find()->select(['msn', 'ak', 'ek', 'utility'])->where(['msn' => $msnArrayFilter]), 'pagination' => false, ]); $models = $dataProvider->getModels(); // Create Excel file $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // Set headers $sheet->setCellValue('A1', 'Msn'); $sheet->setCellValue('B1', 'Ak'); $sheet->setCellValue('C1', 'Ek'); $sheet->setCellValue('D1', 'Utility'); // Fill data $row = 2; foreach ($msnArray as $msn) { // Assuming TaskConfig::find() returns models with the same attributes as the Excel columns $model = TaskConfig::find()->where(['msn' => $msn])->one(); if ($model !== null) { $sheet->setCellValue('A' . $row, $model->msn); $sheet->setCellValue('B' . $row, $model->ak); $sheet->setCellValue('C' . $row, $model->ek); $sheet->setCellValue('D' . $row, $model->utility); $row++; } } // Save the Excel file content to a temporary file $microseconds = microtime(true); // Get current timestamp with microseconds $microseconds = str_replace('.', '', $microseconds); // Remove the dot from microseconds $filename = 'task_config_' . date('YmdHis') . '_' . $microseconds . '.xlsx'; try { // Save Excel file to temporary location $tempFilePath = sys_get_temp_dir() . '/' . $filename; $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save($tempFilePath); // Send the file content to the user for download Yii::$app->response->sendFile($tempFilePath, $filename)->send(); return; } catch (\Throwable $e) { // Handle any exceptions Yii::error('Error generating Excel file: ' . $e->getMessage()); Yii::$app->session->setFlash('error', 'An error occurred while generating the Excel file.'); return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl); } } [/code] Любая помощь будет очень признательна Подробнее здесь: [url]https://stackoverflow.com/questions/78283668/how-to-pass-selected-values-from-view-to-controller-using-select2-in-yii2[/url]