1

I have a channel called "Groups", with a users field type called members for the entries. I need to be able to add/remove users to the members entry field via plugin.

What I've tried is:

// criteria
$criteria = craft()->elements->getCriteria(ElementType::Entry);

// filter
$criteria->slug     = 'groupNameHere';

// section
$criteria->section('groups');

// get entry
$entries = $criteria->find();

foreach($enries as $entry)
{
    // get current members of group 
    $members = $entry['members'];

    // add new user model to $members
    $members[] = craft()->users->getUserByUsernameOrEmail("newUserEmailHere");

    // update field with new $members array
    $entry->getContent()->setAttribute('members', $members);

    // save
    craft()->entries->saveEntry($entry);
}

This simply clears the previous members value for the group, without even adding the new user. I can't find anything online about updating this type of field-type via plugin so I'm just guessing how to do this. Does anyone know the right way to do this?

Any information would hugely help! Thanks!

1 Answer 1

4

When a User field is saved, it takes an array of user IDs only – not complete UserModel objects. Something like this should work:

// get IDs for current members of group 
$members = $entry->members->ids();

// add new user ID to members
$members[] = $addUser->id;

// update field with new $members array
$entry->getContent()->setAttribute('members', $members);

The rest of your code looks fine, except for a minor typo – $enries should be $entries.

2
  • THANK YOU! I can't express my gratitude enough. Just tried it and it worked. :) Out of curiosity and for future reference in troubleshooting, how were you able to see that the user field needed just an array of user IDs?
    – taylor
    Commented Dec 31, 2015 at 8:36
  • 1
    Awesome, happy to help out :) All of the relational fieldtypes (i.e. Entries, Users, Categories, Assets and Tags) take an array of IDs – I honestly can't remember how/where I learned that, though a very easy way to find out how the input data should look for a certain fieldtype is to look at the request headers (e.g. in your browser's dev tools) when the entry is saved in the CP. Other than that, you can look at the relevant classes in the class reference, i.e. UsersFieldType, EntriesService etc., to get a feel for how things are put together. Commented Dec 31, 2015 at 9:45

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.