Adding actions to specific Statamic fields
The recently released field actions feature in Statamic allows you to add custom actions to built-in fieldtypes. By default actions apply to every instance of a particular fieldtype, and you can control the visibility with the visible
function.
So what if you only want to enable an action for a specific instance of a field? You could check the field handle in the visible function, but that isn't very flexible and could become difficult to maintain as fields are added or renamed.
Instead I prefer to use a custom fieldtype config field to control whether a particular action is visible. This allows it to be toggled on and off for specific fields through the blueprint editor. To do this simply add a custom config field in a service providers boot method:
// app/Providers/AppServiceProvider.phpuse Statamic\Fieldtypes\Text;Text::appendConfigField('enable_translate', ['type' => 'toggle','display' => __('Enable Translate'),]);
// app/Providers/AppServiceProvider.phpuse Statamic\Fieldtypes\Text;Text::appendConfigField('enable_translate', ['type' => 'toggle','display' => __('Enable Translate'),]);
And then check for that config value in the action visible
method:
// resources/js/cp.jsStatamic.$fieldActions.add('text-fieldtype', {title: 'Translate',visible: ({ config }) => config.enable_translate,run: ({ ... }) => {// ...},});
// resources/js/cp.jsStatamic.$fieldActions.add('text-fieldtype', {title: 'Translate',visible: ({ config }) => config.enable_translate,run: ({ ... }) => {// ...},});
Adding actions to specific sets
The field action feature also allows you to actions to bard and replicator sets. It's not possible to add custom config fields to set configurations, so if you only want to add an action to a specific set type then checking the set handle is currently the best way to go:
Statamic.$fieldActions.add('replicator-fieldtype-set', {title: 'Generate Content',visible: ({ config }) => config.handle === 'text_block',run: ({ ... }) => {// ...},});
Statamic.$fieldActions.add('replicator-fieldtype-set', {title: 'Generate Content',visible: ({ config }) => config.handle === 'text_block',run: ({ ... }) => {// ...},});