Last active
July 30, 2018 08:26
-
-
Save brandonkelly/8149062 to your computer and use it in GitHub Desktop.
Saving new Matrix data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Get the entry | |
$entry = craft()->entries->getEntryById(100); | |
// Convert the existing data to what it would look like in POST | |
$matrixData = array(); | |
foreach ($entry->matrixField as $block) | |
{ | |
$blockData = array( | |
'type' => $block->getType()->handle, | |
'enabled' => $block->enabled | |
); | |
switch ($block->getType()->handle) | |
{ | |
case 'text': | |
{ | |
$blockData['fields'] = array( | |
'textField' => $block->textField | |
); | |
break; | |
} | |
case 'image': | |
{ | |
$blockData['fields'] = array( | |
'assetsField' => $block->assetsField->ids(), | |
'captionField' => $block->captionField | |
); | |
break; | |
} | |
} | |
$matrixData[$block->id] = $blockData; | |
} | |
// Add new rows | |
$matrixData['new1'] = array( // The 'new' prefix tells Matrix this is a new block | |
'type' => 'image', // 'image' is the block type handle | |
'enabled' => true, | |
'fields' => array( | |
'assetsField' => array(200), // 200 is an asset ID | |
'captionField' => 'Some caption' | |
) | |
) | |
); | |
// Set the new Matrix data | |
$entry->getContent()->matrixField = $matrixData; | |
// Save the entry | |
craft()->entries->saveEntry($entry); | |
/* NOTE: Craft 1.4 will come with APIs that make it possible to directly edit Matrix field data, | |
* without going through the owner element (the entry, in this case). | |
* | |
* The above will still be possible, with one exception: line 50 would need to be rewritten to: | |
* | |
* $entry->setContentFromPost(array('matrixField' => $matrixData)); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found a nasty bug. If you use the gist to add matrix entries, it has a side effect of clearing out other matrix fields associated to the entry. This will only affect you if you have more than one matrix field in your entry.
For example, if I have the following setup:
New Entry called "SXSW 2014".
There are 2 matrix fields; ticketsMatrix and scheduleMatrix.
If you have existing matrix values in ticketsMatrix and scheduleMatrix... and you run the gist above to populate the ticketsMatrix, then all existing values under the scheduleMatrix field will be purge.
Craft is aware of the bug and it should be fixed in version 1.4 of the MatrixService API.