0

As the title says, I can successfully return the "existing user IDs" from an entry field if the "entries.saveEntry" event is called after saving the entry from the CMS admin area; however, if I save an entry via a front-end form, the same code produces empty results.

I've used xDebug to verify that the objects are the same line by line; somehow the data isn't there for $users->ids() for front-end triggered events.

// get entry
$entry = craft()->entries->getEntryById($entryId); // elementType => "Entry"

// get ALL users related to entry
$users = craft()->elements->getCriteria(ElementType::User); // elementType => Craft\UserElementType
$users->status = null;
$users->relatedTo = [$entry]; // elementType => "Entry"
$userIds = $users->ids(); // elementType => Craft\UserElementType

Example result when triggered from backend (good):

array(
    0 => 251,
    1 => 252,
    3 => 257
)

Example result when triggered from front-end (help!):

array()
  • Maybe users are being eager loaded in one case and not the other? craftcms.com/docs/templating/eager-loading-elements – Brad Bell Oct 30 '16 at 2:53
  • Interesting, I'll explore this theory further. – Jarrett Barnett Oct 30 '16 at 4:37
  • Turns out I was inadvertently "emptying" my user field on form post. Essentially I had named one of form fields "fields[customUserFieldName]" which was causing that input to empty the field. Then after that information was saved, it would trigger my entries.saveEntry event method and of course by then, there were no existing ids() to be obtained. – Jarrett Barnett Oct 30 '16 at 5:21
  • Ahh... nice catch. Can you add what worked for you as an official answer in case someone else runs into it? – Brad Bell Oct 30 '16 at 17:31
1

Turns out I was inadvertently "emptying" my user field on form post. Essentially I had named one of the form fields "fields[customUserField]" which upon submitting the form, was saving an empty value into the "Users" field. Then my custom event would trigger and fetch the "Users" field thereby retrieving an empty "array".

So nothing is wrong with the code below:

// get entry
$entry = craft()->entries->getEntryById($entryId);

// get ALL users related to entry
$users = craft()->elements->getCriteria(ElementType::User);
$users->status = null;
$users->relatedTo = [$entry];
$userIds = $users->ids();
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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