0

I want to export my entries to CSV or JSON. Craft 2 had a plugin. I can't find one for Craft 3.

I reached out to the Craft community on Slack. They suggested I try the Craft 3 plugin Beam.

I was told it should be trivia. But, the documentation on Beam is light.

This is the example provided in the Beam documentation to export to CSV:

{% spaceless %}
{% set options = {
header: ['Email', 'Name'],
rows: [
      [ 'test@example.com', 'John Doe' ],
      [ 'another+test@example.com', 'Jane Doe' ],
      [ 'third+test@example.com', 'Trond Johansen' ], 
]
} %}
{{ craft.beam.csv(options) }}
{% endspaceless %}

I want the header to be the field names used in an entry and the rows to be values for each entry in my posts section.

I can't use a loop in the option settings. So, how do I set the options to loop through the entries fields and values?

Thanks

  • Sprout Reports is NOT an option. – Hellyar Jun 25 '18 at 16:48
4

This is what I ended up doing... obviously remove anything that is specific to your project. But this essentially will export all fields and entries from a passed in sectionHandle as a URL Param.

{# @var craft \craft\web\twig\variables\CraftVariable #}
{# @var section \craft\models\Section #}
{% requireLogin %}
{% spaceless %}

    {# Set the section from the optional sectionHandle param, defaulting to 'answers' #}
    {% set section = 'answers' %}
    {% set sectionHandle = craft.app.request.getParam('sectionHandle') %}
    {% if sectionHandle | length %}
        {% set section = sectionHandle %}
    {% endif %}

    {# Get all of the fields from the layout for the CSV header #}
    {% set csvHeader = [] %}
    {% set fields = craft.sections.sectionByHandle(section).getEntryTypes()[0].getFieldLayout().getFields() %}
    {% for field in fields %}
        {% set csvHeader = csvHeader | merge([field.name]) %}
    {% endfor %}

    {# Get all of the entry content for the CSV data #}
    {% set csvData = [] %}
    {% set entries = craft.entries.section(section).all() %}
    {% for entry in entries %}
        {% set csvRow = [] %}
        {% for field in fields %}
            {% set csvRow = csvRow | merge([entry[field.handle]]) %}
        {% endfor %}
        {% set csvData = csvData | merge([csvRow]) %}
    {% endfor %}

    {# Output the data as a CSV file #}
    {% set options = {
        header: csvHeader,
        rows: csvData
    } %}
    {{ craft.beam.csv(options) }}
{% endspaceless %}

...enjoy. This is what was used (with a few additions) in the project: Post-Mortem: LinkedIn Talent Intelligence Experience

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.