Hi guys,

I need some help with the form API. I'm creating an admin module to capture some content management tasks for my client on a single page. This page shows a table with some data and I want my client to be able to export this data to a CSV file.

I can use the form API to build the form with the button etc. But how would I let this export button open up a new browser window that simply dumps a CSV output of the content. Also, this page can only be accessible to logged in users of course.

Any help would be very much appreciated.

Thanks,
Luke

Comments

petebarnett’s picture

Hey Luke,

The Views module is designed for visually building queries, and outputting the results in many forms.
http://drupal.org/project/views

Although views doesn't come with a plugin for CSV export by default, the Views Bonus Pack does...
http://drupal.org/project/views_bonus

Hope this helps.

Peter

pan69’s picture

Hi Peter,

Thanks for your reply. I know about views but I'm not using it. Never will... :)

Cheers,
Luke

petebarnett’s picture

Hi Luke,

In that case, I guess you'd just have to make a page mapping using the menu system, and set the form '#action' attribute to submit to that custom page. For example, in hook_menu() set up your custom url:

    $items['export/csv'] = array(
      'page callback' => 'export_csv',
      'access arguments' => array('foo'),
      'type' => MENU_CALLBACK,
    );

then write the page callback function that does the CSV stuff:

function export_csv() {

	// get the form variables you need from $_REQUEST

	drupal_set_header('Status:200 OK');
	drupal_set_header('Content-Type:text/plain');

	// print your csv content here based on the form result
}

and set the the form submit url to tie it up:

$your_form['#action'] = url('export/csv');

Cheers,
Peter

pan69’s picture

Hi Peter. That makes a lot of sense. Thanks for that!