2

In Craft CMS 3, custom element types support soft-deletion out of the box.

But once soft-deleted, there is now way to restore elements that are now listed in the Trashed status, the only available action is Delete permanently.

enter image description here

How can you make custom elements restorable?

1 Answer 1

4

You have 2 solutions:

  • Implement your own Restore action, or
  • Be lazy and reuse \craft\elements\actions

I won't cover implementing you own action, let's be lazy!

Declare the action

To do this, you need to override the defineActions() method of your element's class:

protected static function defineActions(string $source = null): array
{
    $actions = parent::defineActions($source);

    // Restore
    $actions[] = Craft::$app->getElements()->createAction([
        'type' => \craft\elements\actions\Restoreclass,
        'successMessage' => Craft::t('your-module', 'Elements restored.'),
        'partialSuccessMessage' => Craft::t('your-module', 'Some elements restored.'),
        'failMessage' => Craft::t('your-module', 'Elements not restored.'),
    ]);

    return $actions;
}

Craft will automatically hide the restore action when the selected status is not Trashed (here's how).

The Restore action is now shown when viewing the Trashed elements. enter image description here

But using it will result in a 500 error 😞
Let's fix that.

Add an essentials scenario to your element

craft\elements\actions, tries to validate the elements being restored using the essentials scenario. If your element doesn't have such scenario, restoration will fail.

To add a new scenario, you need to override your element's scenarios() method:

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios[self::SCENARIO_ESSENTIALS] = [ 
        // list here the name of attributes to validate when restoring
    ];

    return $scenarios;
}

You should now be able to restore element 🎉

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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