TransWikia.com

Add matrix block content to newly created Entry

Craft CMS Asked on March 17, 2021

Help. I feel this is almost basic and many have asked similar questions, but I cannot get this to work.

I have an entry type which amongst other things has a Matrix field ph_selectorViews, which has one configured block type in it: phaseView. The block is composed of two fields; an Asset field called viewImage and a Supertable field (not relevant).

After a new entry is created in the CP, I need to create a matrix block (phaseView) in the matrix field (ph_selectorView) and attach an asset to the asset field (viewImage). The asset IDs are valid.

Event handler:

Event::on(
  Entry::class,
  Entry::EVENT_AFTER_SAVE,
  new EntryCreated
);
.
.
.
$entry = $event->sender;
if ($event->isNew && ! ElementHelper::isDraftOrRevision($entry)) {
    // does its thing with $entry, assembles an array of custom field data.
}

Add the field data to the entry:

$entry->setFieldValues($data);
$success = Craft::$app->elements->saveElement($entry);

dump($data):

array:2 [▼
  "ph_aerialViews" => array:1 [▼
    0 => 1322
  ]
  "ph_selectorViews" => array:1 [▼
    "new1" => array:2 [▼
      "type" => "phaseView"
      "fields" => array:1 [▼
        "viewImage" => array:1 [▼
          0 => 1323
        ]
      ]
    ]
  ]
]

$data contains another, Asset field ph_aerialViews which saves just fine.

As far as I can tell, that array that I’m passing to setFieldValues() is correct but the MatrixBlock just isn’t being created or added to the Entry. This process works fine with a single Asset field on the entry (ph_aerialViews) – I can add assets to that programmatically without issue. saveElement returns true, no errors are returned, no exceptions, nothing in the logs.

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP