When I import using JSON with FeedMe Pro and need to import more records into an entry that has a Matrix field. I find it deletes the previous and adds the new data only. Is there anyway to append to the Matrix field leaving the previous data intact?
1 Answer
In addition to How to save Matrix data programmatically in Craft 3
You'll fetch your data loop each row and fetch the element / create a new element if none exists
$section = Craft::$app->sections->getSectionByHandle('news');
$entryTypes = $section->getEntryTypes();
$entryType = reset($entryTypes);
foreach ($jsonData as $row) {
// try to fetch an element
$element = Craft::$app->getElements()->getElementById($row['id']);
// no element exists, create a new one
if ($element === null) {
$element = new Entry(
[
'sectionId' => $section->id,
'typeId' => $entryType->id,
'fieldLayoutId' => $entryType->fieldLayoutId,
'authorId' => 1,
'title' => 'My Entry',
'slug' => 'my-entry',
'postDate' => new DateTime(),
]
);
}
// get the field by handle
/** @var \craft\fields\Matrix $field */
$field = Craft::$app->getFields()->getFieldByHandle('matrix');
// get the existing matrix blocks
$existingMatrix = $element->getFieldValue('matrix');
// serialize the data
$serializedMatrix = $field->serializeValue($existingMatrix, $element);
// loop your json matrix blocks
foreach ($row['yourMatrixBlocks'] as $key => $block) {
// append your new Matrix fields
$serializedMatrix['new' . $key] = [
'type' => 'block',
'fields' => [
'field' => $block['field']
],
];
}
// set the new field value
$element->setFieldValue('matrix', $serializedMatrix);
$success = Craft::$app->getElements()->saveElement($element);
// display errors - just in Case
if($success === false){
Craft::dd($element->getErrors());
}
}
-
Excellent! I was hoping it was not beyond me, I am so far away from being a dev, I am a digital marketer filling in to get this working. My Matrix field has a Table field in it too. I have to see what I can do with it, but thank you!– VinCommented May 2, 2018 at 8:22
-
The easiest way to get the data structure for the required field type is to take a look at your
$_POST
variable when you save an element in your CP. Commented May 2, 2018 at 8:27 -
Makes sense, I have current entries I need to update so gotta see with spending some time taking a go at it.– VinCommented May 2, 2018 at 8:32
-
I have around 10,000 records to import in, so thinking this may be a solution best suited for FeedMe if I can get it to work.– VinCommented May 2, 2018 at 8:52
-
You can change the code in FeedMe as well if you want Commented May 2, 2018 at 8:56