Change matrixblock field value before save element So i have a Matrix with one type of matrixblocks.
These all have a field for a custom id which should be set by the system, if empty, before the entry is saved.
I can access the individual matrixblocks and change the field value in all of them. But i am not sure how to add them back to the matrix so the changes will apply.
example code that is not working:
After a bit of testing, it appears you don't have anything to do to have your values saved, just set them and Craft will take care of the rest.
    Event::on(
        Elements::class,
        Elements::EVENT_BEFORE_SAVE_ELEMENT,
        static function (ElementEvent $event) {
            $element = $event-&gt;element;
            if ($element instanceof Entry &amp;&amp; $element-&gt;getSection()-&gt;handle === 'testSection') {
                /** @var MatrixBlock[] $blocks */
                $blocks = $element-&gt;getFieldValue('testMatrix')-&gt;all();
                foreach ($blocks as $block) {
                    $block-&gt;setFieldValue('automaticField', uniqid('some unique value', false));
                }
            }
        }