I'm building a plugin which needs to add users to a users-type field when they edit the entry on the front-end. It works well when the post is created, adding the original author to the field, and again when the same user edits the post. However, when another user edits the post everything comes to a standstill for a minute and users are taken not to the landing page, but to a page containing nothing other than a "1". Checking the back-end, it has added the second user to the field, though.
Can anyone suggest to me from the code below why adding a second (haven't tested any more than that yet) user brings things the server to its knees?
public function init()
{
parent::init();
// ON SAVE ENTRY
craft()->on('entries.saveEntry', function(Event $event) {
$entry = $event->params['entry'];
$user = craft()->userSession->getUser();
$notifyMe = craft()->request->getPost('notifyme');
// CHECK THIS IS THE FORUM SECTION
if ($entry->sectionId == 16) {
craft()->notifier->addAnotherUserToNotify($entry, $user, $notifyMe);
}
});
}
And here is the function:
// ADD ANOTHER USER TO A POST'S NOTIFICATION LIST
public function addAnotherUserToNotify($entry, $user, $notifyMe)
{
if ($notifyMe == "yes") {
// GET IDs OF USERS ALREADY LISTED TO BE NOTIFIED
$usersToNotify = $entry->usersToNotify->ids();
if ( ! in_array( $user->id, $usersToNotify ) ) {
// ADD THE CURRENT USER TO THE ARRAY OF USERS TO BE NOTIFIED
$usersToNotify[] = $user->id;
}
// UPDATE THE ENTRY'S FIELD WITH THIS UPDATED ARRAY
$entry->getContent()->setAttribute('usersToNotify', $usersToNotify);
// SAVE ENTRY
craft()->entries->saveEntry($entry);
}
}
The code is inspired by Update User "Field Type" for Entry in Plugin
addAnotherUserToNotify
method, my guess is you've created an endless loop with callingsaveEntry
within theentries.saveEntry
event listener.