2

I'm trying to update a specific field (a dropdown) in an existing block (of type 'subhoofding') in an existing matrix field 'contentBuilder' The migration itself runs fine, show the new value as output, but some bizarre reason it gets not saved to the database.

public function safeUp()
    {
        $sites = Craft::$app->sites->getAllSites();

        foreach($sites as $site) {
            //craft::dd($site->id);
            $contact = Entry::find()->slug('contact')->siteId($site->id)->one();
         

            // Read content from matrix field
            $blocks = $contact->getFieldValue('contentBuilder')->all();

            foreach($blocks as $block) {
                //craft::dd($block->type);
                if ($block->type == "subhoofding") {
                    echo("old value = " . $block->getFieldValue('alignering') . "\n");  
                    
                    $block->setFieldValue('alignering', 'center');
                    echo("new value = " . $block->getFieldValue('alignering') . "\n");

                } 

            }


            // And save the entry contact
            $success = \Craft::$app->elements->saveElement($contact);
            if ($success) {
                echo("SUCCESS \n");
            }

            echo ("  --- on to next site ----  \n");
    }
    return true;

1 Answer 1

2

Matrix blocks are, essentially, standalone elements (just like entries, users and assets) that just happen to have an owner element. As such, you'll want to (re)save the block elements themselves in this case; not the owner element (i.e. the "contact" entry containing the Matrix field).

Try amending your inner foreach loop to this:

foreach($blocks as $block) {
    if ($block->type == "subhoofding") {
        // Set new field value
        $block->setFieldValue('alignering', 'center');
        // Re-save the block
        \Craft::$app->getElements()->saveElement($block);
    }
}
1
  • 1
    thanks very much Mats. I wasn't aware of this and can confirm this works! Commented Dec 23, 2022 at 14:35

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.