I have an entry that has a matrix field. From a controller in a module I want to add additional data to it (e.g. some text that I have in a variable $messageText) but without overwriting the existing blocks.

So far I have in my controller:

public function actionPostMessage() {
        $request = new \craft\web\Request;

        // this is the text (from a POST request) that I want to 
        // add to the matrix field
        $messageText = $request->post('messageText');

        $entryId = $request->post('applicationId');
        $currentUser = Craft::$app->getUser()->getId();

        // I can get the entry all right:
        $entry = Entry::find()

        // and this is the matrix query object where I want to add the  
        // $messageText received from a post request
        $messages = $entry->messages;

I can loop through $messages and get the existing messages without problems:

        foreach ($messages as $message) {
            $temp = $message->messageText;

But how can I append the new text from the $messageText variable to it without overwriting the existing data already in the matrix field?

EDIT: I found this info on Github: Creating / editing single matrix blocks on the front end #5717 and based on that info I have added the following code:

        $sortOrder = (clone $entry->messages)->anyStatus()->ids();
        $sortOrder[] = 'new:1';

        $newBlock = [
            'type' => 'textMessage',
            'fields' => [
                'messageText' => $messageText,
                'outgoing'    => true,
                'messageRead' => false,

        $entry->setFieldValue('messages', [
            'sortOrder' => $sortOrder,
            'blocks' => [
                'new:1' => $newBlock,

        try {
            $success = Craft::$app->elements->saveElement($entry);
        } catch (ElementNotFoundException $e) {
            echo $e;
            echo 'Element not found.';
        } catch (Exception $e) {
            echo $e;
            echo 'Element not saved';

It does not throw any errors and $success is true, but nothing is updated in the DB/new message does not appear there.

Any ideas what may be missing here? Why it is not saving the new block in the matrix field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.