1

I need to update existing entries after the creation of a checkbox fields, to apply the default value to everything that was created before the availability of the new field. The code should run in a migration to be deployed along the changes in the project config.

What is the correct way to programmatically set checkboxes (craft\fields\data\MultiOptionsFieldData)?

I verified the migration updates the entry (the title for instance), but not the custom field:

$entries = \craft\elements\Entry::find()
  ->section('sectionProduct')
  ->all();

foreach($entries as $entry) {
  $options = $entry->distribution->getOptions();
  foreach($options as $opt) {
    $opt->selected = true;
  }
  $entry->distribution->setOptions($options);
  Craft::$app->getElements()->saveElement($entry);
}

After running the migration, the control panel never shows the checkboxes flagged (the checkbox field has two possible values).

TIA

1

Sleeping on it (and peeking at the db) provided a solution, with even simpler code:

$entries = \craft\elements\Entry::find()
  ->section('sectionProduct')
  ->all();

foreach($entries as $entry) {
  $entry->setFieldValue('distribution', ["1", "2"]);
  Craft::$app->getElements()->saveElement($entry);
}

where "1" and "2" are the values associated to the checkboxes.

If you know the checkbox values, use setFieldValue and pass them as an array:

  • [] (empty) no checkboxes selected
  • ["single value"]
  • ["multi", "values"]

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.