2

I have set up a custom search of entries on a page in my Craft site which includes filters to filter the results. I would like to be able to export these results (filtered or otherwise) as a CSV through a link on the page: http://www.joycefdn.org/grants

Is there a way to do this?

4

You can just make link to a twig template to output a csv quite simply...just like any other template really, except it won't extend you layout etc. and will simply contain something like:

{%for result in results %}
    {{var1}},{{var2}},{{var3}} etc...
{% endfor %}

Depending on what sort of csv you're after and what you're going to do with the data, you may want to consider escaping the data as you output it:

http://twig.sensiolabs.org/doc/filters/escape.html

In terms of setting it up as a link, your csv template could just accept the same search parameters passed through and essentially repeat the search and output the csv results as above.

I.e. in your original results page you could build the link to the CSV as

<a href="/utility/csvmaker?q={{q}}">Get Results As CSV</a>

And then in the csvmaker

{% set results = craft.entries.search(q).order('score') %}
...etc as above

But a lot depends on how you've built your search in the first place really.

If you want it to trigger an actual file download, then I've found that's pretty easy to do that on the front end with some JS, e.g. I use this:

https://stackoverflow.com/questions/19721439/download-json-object-as-a-file-from-browser/20343999

| improve this answer | |
  • Thanks for the answer! I am working on implementing your solution and have just run across a few things, sorry but I'm fairly new to Craft... For the route you suggest in escaping, how do you extend Craft to use the csv custom escaper? and for the force download, that method did not work for me. I included the script as listed and there was no change in behavior when the link was clicked. – Elisa C Oct 31 '16 at 23:46
  • @ElisaC Well you can either use one of the standard twig escape filters, or you'd have to write your own twig filter in a plugin which is broadly described here: twig.sensiolabs.org/doc/advanced.html ... it's not too hard to write a filter in practise (look for a plugin with an existing one to copy), but that's an SE question in it's own right if you need it. The force download thing I would attempt after just getting it to work as a standard link - it shouldn't be too hard to adapt that JS but will be easier to help if you have something concrete working otherwise I think. – Jeremy Daalder Nov 1 '16 at 1:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.