-
-
Save bwlng/5c0bdeff62fabe247c87 to your computer and use it in GitHub Desktop.
Add matrix rows to an entry through a plugin
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 | |
namespace Craft; | |
/** | |
* Plugin service | |
*/ | |
class PluginService extends BaseApplicationComponent | |
{ | |
// Optionally pass in an entry ID | |
public function addMatrixBlockToEntry($entryId = null) | |
{ | |
if ($entryId) { | |
$entry = craft()->entries->getEntryById($bundleId); | |
// True if entry actually exists | |
if ($entry) | |
{ | |
// An entry exists, so add the Matrix block | |
$this->addBlockToMatrix($entry); | |
} | |
else | |
{ | |
Craft::log('Couldn’t find a valid entry to add the matrix to.', LogLevel::Error); | |
} | |
} | |
else | |
{ | |
// No entry, so create one | |
$this->createEntry(); | |
} | |
} | |
// Create an entry then create a Matrix block | |
public function createEntry() | |
{ | |
$entry = new EntryModel(); | |
$entry->sectionId = 1; | |
$entry->typeId = 1; | |
$entry->enabled = true; | |
$entry->getContent()->setAttributes(array( | |
'title' => "Hello World!" | |
)); | |
$success = craft()->entries->saveEntry($entry); | |
if ($success) { | |
// Entry was saved successful, add a Matrix block | |
$this->addBlockToMatrix($entry); | |
} | |
else | |
{ | |
Craft::log('Couldn’t save the entry "'.$entry->title.'"', LogLevel::Error); | |
} | |
} | |
// Add a Matrix block to an exisiting entry | |
public function addBlockToMatrix($entry) | |
{ | |
$ownerId = $entry->id; // the parent entry | |
$block = new MatrixBlockModel(); | |
$block->fieldId = 245; // Matrix field's ID | |
$block->ownerId = $ownerId; // ID of entry the block should be added to | |
$block->typeId = 47; // ID of block type | |
$block->getContent()->setAttributes(array( | |
'text' => "Text for the new block", | |
)); | |
$success = craft()->matrix->saveBlock($block); | |
if (!$success) | |
{ | |
Craft::log('Couldn’t save the entry "'.$entry->title.'"', LogLevel::Error); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment