Skip to content

Instantly share code, notes, and snippets.

@robertbanh
Forked from brandonkelly/gist:8149062
Created December 27, 2013 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertbanh/8149297 to your computer and use it in GitHub Desktop.
Save robertbanh/8149297 to your computer and use it in GitHub Desktop.
<?php
// Get the entry
$entry = craft()->entries->getEntryById(100);
// Define the new Matrix data
$matrixData = array(
'1' => array( // '1' is an existing block ID
'type' => 'text', // 'text' is the block type handle
'enabled' => true,
'fields' => array(
'textField' => 'Lorem ipsum' // 'textField' is the field handle
)
),
'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 26 would need to be rewritten to:
*
* $entry->setContentFromPost(array('matrixField' => $matrixData));
*/
@robertbanh
Copy link
Author

Relationship fields:

// Grab existing relational IDs
$newIds = $entry->myEntriesField->ids();

// Add any new IDs
$newIds[] = $newEntry->id;

// Set them back on the relational field
$entry->myEntriesField = $newIds;

// Go through the entries service to let it save everything.
craft()->entries->saveEntry($entry);

@robertbanh
Copy link
Author

Fetching Matrix fields:

$criteria = craft()->elements->getCriteria(ElementType::MatrixBlock);
$criteria->ownerId = 100; // entry->id
$criteria->fieldId = 5; // matrix field id
$blocks = $criteria->find();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment