craftcms / cms

Build bespoke content experiences with Craft.
https://craftcms.com
Other
3.22k stars 626 forks source link

Custom element exports #5090

Closed lukeholder closed 4 years ago

lukeholder commented 4 years ago

Plugins and modules should have a way to define custom element export options.

Would resolve craftcms/commerce#976

brandonkelly commented 4 years ago

This has been added for Craft 3.4. There is now a new ElementExporterInterface that custom element export classes can implement, and they can be registered with a new EVENT_REGISTER_EXPORTERS event on element types.

use craft\elements\Entry;
use craft\events\RegisterElementExportersEvent;
use yii\base\Event;

Event::on(
    Entry::class,
    Entry::EVENT_REGISTER_EXPORTERS,
    function(RegisterElementExportersEvent $event) {
        $event->exporters[] = MyElementExporter::class;
    }
);
bwatabu55 commented 2 years ago

Is it possible to only show your custom export type option when viewing specific entry listings or is there no way to control the display? Since the data I am customly exporting only pertains to a specific entry type, it produces an error when trying to execute it while viewing a different entry listing.

I tried to register a JS code snippet to try and hide the export option but its unable to do so since the JS executes before the entry listing is fully loaded. Any solutions? Thanks!

brandonkelly commented 1 year ago

@bwatabu55 The available exporters are defined per source. So yes, your event handler can conditionally register the exporter, when a particular source is selected:

use craft\elements\Entry;
use craft\events\RegisterElementExportersEvent;
use yii\base\Event;

Event::on(
    Entry::class,
    Entry::EVENT_REGISTER_EXPORTERS,
    function(RegisterElementExportersEvent $event) {
        if ($event->source === 'someSourceKey') {
            $event->exporters[] = MyElementExporter::class;
        }
    }
);
jonleverrier commented 1 year ago

@brandonkelly How do you go about removing an exporter?

I've made my own and want to remove the default ones that come with craft/commerce.

jonleverrier commented 1 year ago

To answer my own question:

$event->exporters = []; // removes default exporters
$event->exporters[] = elements\exporters\MyExporter::class;
brandonkelly commented 1 year ago

Yep, or just

$event->exporters = [
    elements\exporters\MyExporter::class,
];