0

I am trying to display a notification to the user in CP, if the entry is having a draft so that the next user won't redo/overdo the other draft. For that how do we find the entry has drafts?

1 Answer 1

1

You can use \craft\services\Drafts::getEditableDrafts to find drafts that the user can edit for the given entry:

$drafts = Craft::$app->getDrafts()->getEditableDrafts($entry);

If you want to bypass the permission check and find any drafts for the entry, regardless of permissions and current user, you can use an entry query. Use draftOf to limit the query to drafts of the given entry and status(null) to allow the query to return drafts:

$drafts = Entry::find()
    ->draftOf($entry)
    ->siteId($entry->siteId)
    ->status(null)
    ->orderBy(['dateUpdated' => SORT_DESC])
    ->all();

This will always return an array of drafts, which may be empty if there aren't any. If all you care about is whether a draft exists, you can execute the query with exists() instead of all(), which will just return a boolean true or false.

5
  • Thanks for the details in addition to the above, could you point me to how to display an html notification on the control panel?
    – Parthiban
    Commented Sep 5, 2022 at 3:13
  • 1
    @Parthiban Craft refers to those notifications as flash messages, you can set them through the session component. See here and here for details.
    – MoritzLost
    Commented Sep 5, 2022 at 7:43
  • Thanks, @moritzlost But the above solutions won't display permanently(after certain seconds it will auto-hide). I was looking to show a notification permanently. Currently, I append HTML elements with JS. Let me know if there are any specific notification methods we can use.
    – Parthiban
    Commented Sep 5, 2022 at 14:28
  • 1
    @Parthiban In Craft 4 there's a new setting for the default duration that flash messages are visible for, you can set the notificationDuration as part of the accessibilityDefaults. You can set that to 0 to show the messages indefinitely, though users can still change that in their account. That setting is only available in the latest Craft 4 version, though. I don't think there's another convenient method for this, so appending messages in JS sounds reasonable.
    – MoritzLost
    Commented Sep 6, 2022 at 7:29
  • 1
    Thanks for the details @moritzlost
    – Parthiban
    Commented Sep 6, 2022 at 9:48

Your Answer

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

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