Feel like I'm going crazy here...

I've got this snippet of code.

I find my entry based on title key/value.

I find my category ids based on alcohol key/value.

I attempt to set the entry category relation and save.

I get no errors. But nothing is saved either.

I've found other similar questions but nothing is working.

Need a fresh pair of eyes...

    $entriesWithAlcohol = [
                    'title' => 'Jupiter Hotel + NEXT',
                    'alcohol' => ['byo', 'byo-with-corkage-fee'],
            foreach ($entriesWithAlcohol as $entryWithAlcohol) {
                $entry = \craft\elements\Entry::find()->title(\craft\helpers\Db::escapeParam($entryWithAlcohol['title']))->one();
                if ($entry) {
                    $categoryIds = [];
                    foreach ($entryWithAlcohol['alcohol'] as $alcoholValue) {
                        $category = \craft\elements\Category::find()->slug(\craft\helpers\Db::escapeParam($alcoholValue))->one();
                        if ($category) {
                            $categoryIds[] = $category->id;
                    $entry->setFieldValue('alcoholWip', $categoryIds);
                    if (Craft::$app->elements->saveElement($entry)) {
                        Craft::info('Entry updated (ID: '.$entry->id.').');
                    } else {
                        Craft::error('Could not updated the entry (ID: '.$entry->id.').', LogLevel::Error);

1 Answer 1

$entry->setFieldValue('alcoholWip', array_values($categoryIds));

Forgot to use array_values to pass in the values only, not the key/value pairs.

See, I told you I was going crazy!!

  • Glad you got it sorted. Hi from PDX! 🌹 Oct 2, 2021 at 6:52

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.