Skip to content

Instantly share code, notes, and snippets.

@btpoe
Created June 9, 2017 17:04
Show Gist options
  • Save btpoe/215c34ac6da5a7d85f557082418024d7 to your computer and use it in GitHub Desktop.
Save btpoe/215c34ac6da5a7d85f557082418024d7 to your computer and use it in GitHub Desktop.
<?php
namespace vendorName\pluginName\controllers;
use Craft;
use craft\helpers\Assets;
use craft\elements\Asset;
use craft\elements\Entry;
use craft\web\Controller;
class ExampleController extends Controller {
public function saveExampleEntry($exampleId)
{
$entry = Entry::find()->section('examples')->igdbId($exampleId)->one();
if ($entry) {
return $entry->id;
}
$data = $this->getExampleData($exampleId);
$section = Craft::$app->sections->getSectionByHandle('examples');
$entryType = $section->getEntryTypes()[0];
$entry = new Entry();
$entry->sectionId = $section->id;
$entry->typeId = $entryType->id;
$entry->fieldLayoutId = $entryType->fieldLayoutId;
$entry->authorId = Craft::$app->getUser()->getIdentity()->id;
$entry->title = $data->name;
$entry->slug = $data->slug;
$entry->setFieldValues([
// add custom fields here...
'someProp' => $data->someProp,
'anotherField' => $data->anotherField,
'relatedAsset' => $this->saveRelatedAsset($entry, $data->imageUrl),
]);
if (!Craft::$app->getElements()->saveElement($entry)) {
return ['status' => 'error', 'errors' => $entry->getErrors()];
}
return ['status' => 'success', 'id' => $entry->id];
}
private function saveRelatedAsset($entry, $url)
{
$fieldId = 3; // get the proper field id
$field = Craft::$app->getFields()->getFieldById($fieldId);
$folderId = $field->resolveDynamicPathToFolderId($entry);
$asset = new Asset();
// TODO: need to finish this method.
return $asset->id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment