Update checkbox value through plugin (Craft 3) 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-&gt;fieldHandle-&gt;getOptions(), then manipulating the resulting array, then set the value with $entry-&gt;fieldHandle-&gt;setOptions()

$contact = Entry::find()
    -&gt;id(...)
    -&gt;one();
$newsletters = $contact-&gt;contactNewsletterSubscriptions-&gt;getOptions();
$newsletters[$index]-&gt;selected = false;
$contact-&gt;contactNewsletterSubscriptions-&gt;setOptions($newsletters);
Craft::$app-&gt;elements-&gt;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-&gt;contactNewsletterSubscriptions-&gt;serialize());
$index = array_search($newsletterName, $newsletterSubscriptions);
unset($newsletterSubscriptions[$index]);
$contact-&gt;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.
You need to set the field value, not the options

$entry-&gt;setFieldValue('fieldHandle' [
    'value1', 'value2'
});
Craft::$app-&gt;getElements()-&gt;saveElement($entry);


If you want to change the values, the easiest method is

$allOptions = $entry-&gt;getFieldValue('fieldHandle');
$selected = [];
foreach($allOptions as $option){
    if($option-&gt;selected){
         $selected[] = $option-&gt;value;
    }
}
// unset a value
unset($selected[1]);
// add another value
$selected[] = 'anotherValue';
$entry-&gt;setFieldValue('fieldHandle', $selected);
Craft::$app-&gt;getElements()-&gt;saveElement($entry);


edit

Another approach - a little bit less code and more general since it's the same for every single field in Craft - but more resource heavy

$field = Craft::$app-&gt;getFields()-&gt;getFieldByHandle('handle);
$selected = $field-&gt;serializeValue($entry-&gt;getFieldValue('handle'), $entry);
$selected[] = 'anotherValue';
$entry-&gt;setFieldValue('handle', $selected);
Craft::$app-&gt;getElements()-&gt;saveElement($entry);