Joomla - Force File Download / CSV Export

Posted by lautaro.dragan on Stack Overflow See other posts from Stack Overflow or by lautaro.dragan
Published on 2013-11-05T03:21:00Z Indexed on 2013/11/06 3:54 UTC
Read the original article Hit count: 338

Filed under:
|
|

I'm in need of help... this is my first time asking a question in SO, so please be kind :)

I'm trying to force-download a file from php, so when the user hits a certain button, he gets a file download. The file is a csv (email, username) of all registered users.

I decided to add this button to the admin > users screen, as you can see in this screenshotenter image description here.

So I added the following code to the addToolbar function in administrator/components/com_users/views/users/view.html.php:

JToolBarHelper::custom('users.export', 'export.png', 'export_f2.png', 'Exportar', false);

This button is mapped to the following function in the com_users\controller\users.php controller:

public function exportAllUsers() {
    ob_end_clean();
    $app = JFactory::getApplication();

    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=ideary_users.csv");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo "email,name\n";

    $model = $this->getModel("Users");
    $users = $model->getAllUsers();

    foreach ($users as $user) {
        echo $user->email . ", " . ucwords(trim($user->name)) . "\r\n";
    }

    $app->close();

}

Now, this is actually working perfectly fine.

The issue here is that after I download a file, if I hit any button in the admin that causes a POST, instead of it performing the action it should, it just downloads the file over again! For example:

  • I hit the "Export" button
  • "users.csv" downloads
  • Then, I hit the "search" button
  • "users.csv" downloads... what the hell?

I'm guessing that when I hit the export button, a JS gets called and sets a form's action attribute to an URL... and expects a response or something, and then other button's are prevented from re-setting the form's action attribute. I can't think of any real solution for this, but I'd rather avoid hacks if possible.

So, what would be the standard, elegant solution that joomla offers in this case?

© Stack Overflow or respective owner

Related posts about php

Related posts about csv