I'm trying to update a checkbox field of an entry through a plugin service. I tried two things:
Get the field values with
$entry->fieldHandle->getOptions()
, then manipulating the resulting array, then set the value with$entry->fieldHandle->setOptions()
$contact = Entry::find() ->id(...) ->one(); $newsletters = $contact->contactNewsletterSubscriptions->getOptions(); $newsletters[$index]->selected = false; $contact->contactNewsletterSubscriptions->setOptions($newsletters); Craft::$app->elements->saveElement($contact);
(where $index is the array index of the setting I want to change)
-> this didn't work (no error message, changes just didn't get saved)
If I make a var_dump of
$contact
, the field contactNewsletterSubscriptions is showed as string. I played around with json_decode and serialize to get the right formatting (it looks exactly as when doing a var_dump):$newsletterSubscriptions = json_decode($contact->contactNewsletterSubscriptions->serialize()); $index = array_search($newsletterName, $newsletterSubscriptions); unset($newsletterSubscriptions[$index]); $contact->contactNewsletterSubscriptions = (string)json_encode(array_values($newsletterSubscriptions))
-> doesn't work either; value gets saved as string; if I later call getOptions() on the field I'm getting "Call to a member function getOptions() on string"
Any idea how I can change the status of a checkbox from selected = true to selected = false?
Best regards.