0

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: enter image description here

  • 1
    Where do you use this code? In a module? If so it would help to know which event you hook to, if any, or if it's in a controller action. Have you tried $execution->save()? – nstCactus Sep 17 at 19:10
  • I am using this code inside a module. It is triggered inside the EVENT_BEFORE_SAVE_ELEMENT Event. – Leonardo Sep 18 at 6:41
0

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->element;
            if ($element instanceof Entry && $element->getSection()->handle === 'testSection') {
                /** @var MatrixBlock[] $blocks */
                $blocks = $element->getFieldValue('testMatrix')->all();
                foreach ($blocks as $block) {
                    $block->setFieldValue('automaticField', uniqid('some unique value', false));
                }
            }
        }
| improve this answer | |
  • This did not work for me. I implemented it the same way as you but the changes were not applied and not shown in the ControlPanel edit page. – Leonardo Sep 18 at 15:30
  • Okey so i handled my problem for the after save in another way. But would you know how to save it in, lets say, a controller? Getting the element via an id , then change the field value of certaint matrix blocks and then resave it? – Leonardo Sep 22 at 8:58
  • Not tested but I guess you could just call the save() method on the element after making your changes. But if my previous code example didn't work for you, I'm afraid just calling save() might not be enough. Can you explain what you did in the after save? – nstCactus Sep 22 at 9:31
  • This irritates me. A save() function on MatrixBlocks does not exist for me. Or are we both talking about different things? After Save: We are now generating and saving a custom id on the element. If the custom id of each matrix block is needed, a combination from the element's custom id and the matrix block id is generated inside a simple sevice. – Leonardo Sep 25 at 8:02
  • I'm talking about the save() method on the element owning the matrix field (this is most probably an Entry). – nstCactus Sep 25 at 11:30

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.