2

I have a channel called 'Activities' and a channel called 'Members'. In 'Activities' I have a field called 'Accepted'. I want to be able to add and remove 'Members' to the field 'Accepted'. I want to do this in a plugin that I am building. Is there a method to add or delete a single 'Member' to the 'Accepted' field of an 'Activity'? Basically is should remove the relationship between the Activity and the Member, but it should not remove the Member itself.

4

A relationship field expects an array of element IDs. So to remove a user, you'd just get all the current IDs and remove the one you want to delete.

// Get the current member IDs
$members = $entry->accepted->ids();

// Remove a member ID
$key = array_search(52, $members); 
if ($key !== false) {
    unset($members[$key]);
}

// Add a new member ID
$members[] = 83;

// Update the member IDs
$entry->setContentFromPost(array(
    'accepted' => $members
));
0
1

Yes, your Accepted field should be an Entries custom field.

You can limit the field to only allow you to select entries from the Members Channel. e.g. you would only tick the 'Members' source (see image)

enter image description here

This would allow you to select (or remove) one or more Member entries, when publishing or editing an Activity entry.

More info in the docs, here: https://craftcms.com/docs/entries-fields

3
  • I have already set up the Activities and Members as you described above, but I need a php method in my plugin to add Members to and remove Members from activities. Do you know how I would write this in php?
    – SiteHopper
    Mar 29 '16 at 13:18
  • Please give us more info... Could you describe the basis on which you would add/remove a Member from an Activity?
    – Matt P
    Mar 29 '16 at 15:17
  • 1
    I want to add/remove the Member via an API entry point in my custom plugin. So the user makes a request to this entry point, and then I add/remove him from the activity.
    – SiteHopper
    Mar 29 '16 at 15:47

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.