Hello. I have a controller action that returns a file (most of the time), but when the file is empty, I don’t wanna return that, and I wanna get the (index) view untouched (like when the action returns a file with content).
How I can do that? I tried all, and allways get a white screen (but without any errors).
Thanks
Stefano, the “render” function refresh the page. I have a index view with filters applied by the user. I don’t wanna change the view. I wanna do “nothing” when the file is empty.
So where are you checking if the file is empty?
Because if it is empty then it will show blank screen and when download succeeds it will close that tab automatically
By that time it is too late!
I would suggest you check existence of the file in the action that renders the link. And render the link if file exists and message otherwise.
Another way would be to render file in the same action something like
class MyController extends Controller
{
public function actionDownloadFile($id, $download = 0)
{
if ($download == 1) {
$file = "something done here";
if ($file != null) //or any empty file check
{
return $file; //do your file stuffs
} else {
Yii::$app->session->setFlash('danger', 'Failed to download for some reason!');
}
}
return $this->render('myview', ['somedata' => $data]);
}
}
A bit more complicated, but I think you can do this with Ajax.
First an Ajax call for finding out if the file is ok. (Save selected file id, locally I guess.)
On return, programmatically click a hidden link for creating the pdf and spawn the new window with target=_blank.
Just an idea.
Edit: I had missed to add target=_blank. Obviously this will not pass the popup blocking. Thus as bad as w=window.open, which is required for w.close() to work.