Skip to content

Instantly share code, notes, and snippets.

@silentworks
Forked from benjamminf/neo_create_block.php
Created July 31, 2017 17:49
Show Gist options
  • Save silentworks/ef496823c1a977048752489c927e8dd1 to your computer and use it in GitHub Desktop.
Save silentworks/ef496823c1a977048752489c927e8dd1 to your computer and use it in GitHub Desktop.
Create Neo block and save it to entry
<?php
// Get the entry model. This could really be any element model, such as a category or Craft Commerce product.
$entry = craft()->entries->getEntryById(1234);
// Get the Neo field model and the field type model.
$field = craft()->fields->getFieldByHandle('neoFieldHandle');
$fieldType = $field->getFieldType();
$fieldType->setElement($entry);
// Get the structure model for the Neo field. The block needs to be added to the structure since Neo field have hierarchy.
$structure = craft()->neo->getStructure($fieldType);
// Get the block type you want to create a block from.
$blockTypes = craft()->neo->getBlockTypesByFieldId($field->id, 'handle');
$blockType = $blockTypes['blockTypeHandle'];
// Create the block model.
$block = new Neo_BlockModel();
$block->fieldId = $field->id;
$block->ownerId = $entry->id;
$block->typeId = $blockType->id;
$block->ownerLocale = $entry->locale;
// Save the block first, then add it to the structure.
craft()->neo->saveBlock($block);
craft()->structures->appendToRoot($structure->id, $block);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment