1

Is it possible to update an entry’s Users field from the front-end? If so, how would you go about it?

The situation is this: training events are created and then posted for members to bid on for a limited number of spots. Logged in members review the available events and add their name (would use their ID) to each event of interest. Admins then manually chose a select few from all submissions.

I know I can do this by adding their IDs to a text field in the event section, and then using Split to create an array, but the Users field approach is much more elegant and offers more flexibility.

2

You would need to do this with a plugin that provides a custom controller, which looks at the post data and modifies the entries’ Users fields accordingly.

The controller action would look something like this:

<?php

$entryIds = craft()->request->getPost('entries');

if ($entryIds && is_array($entryIds))
{
    // Get the current user's ID
    $currentUserId = craft()->userSession->getUser()->id;

    // Fetch the entries
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->id = $entryIds;
    $entries = $criteria->find();

    foreach ($entries as $entry)
    {
        // Update the Users field value with the current user's ID
        $userIds = $entry->myUsersField->ids();
        $userIds[] = $currentUserId;

        $entry->setContentFromPost(array(
            'myUsersField' => $userIds;
        ));

        craft()->entries->saveEntry($entry);
    }
}
2
  • Thanks for the reply, Brandon. What I meant was a "Users field type", not a field in a user's profile. What I am trying to do is update a Users field in a channel entry, with a front end form that would add a logged in user's ID to a specific channel entry, via a Users field.
    – Roi Agneta
    Apr 4 '16 at 15:09
  • @RoiAgneta Ah sorry, misunderstood. I just updated my answer :) Apr 4 '16 at 23:00

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.