i simply can not get my "job" done. I try to create a plugin for Craft, a simple one. It reads some date and should create new entries out of this data. First i stuck on a stupid save-mistake, someone here helped me get my error :)
Now, i can create and save an entry. But i can not add a category, an image or a matrix-based entry. I tried several old craft 2 tutorials and got with the categories to Craft::$app->relations->saveRelations, but after i got rid of all errors, it saves my entry, create a ne row in my database relation table, but in the entry, i can not find the relation. The database row in relations seems to be incorrect. Last version of my code: i tried to convert this Problem/Example into my version in craft 3. No success :(
I think, if i understand my problem, i will be able to create several relations, because categories, Assets and so on are just types of fields. And they are related to the entries - am i right ?
I'll show my current code.....has anyone a good advise or an example how to add a relation(category) and how to create and add an image asset ?
$section = Craft::$app->sections->getSectionByHandle('mychannelentryhandle'); $entryTypes = $section->getEntryTypes(); $entryType = $entryTypes[0]; $entry = new \craft\elements\Entry(); // $entry->id = $uid; $entry->title = $title; $entry->sectionId = $section->id; $entry->typeId = $entryType->id; $entry->siteId = 1; $entry->authorId = 1; $entry->enabled = true; // TODO: Decide if published or not $entry->postDate = $postDate; $entry->slug = 'test_' . $uid; if (Craft::$app->elements->saveElement($entry)) { echo 'New entry created successfully.'; // SAVE CATEGORY RELATION $field = Craft::$app->fields->getFieldByHandle('categoryfieldhandle'); try { $relationsIds[] = $entry->id; Craft::$app->relations->saveRelations($field, $category, $relationsIds); } catch (\Exception $e) { // Something went wrong – return `false` or an error message, log the exception? print_r('ERROR WHILE SAVING CATEGORY'); print_r($e->getMessage()); return false; } // Save the new Relation Craft::$app->elements->saveElement($entry); $result = true; } else { echo 'Could not save the new entry.' . "\n"; print_r($entry->getErrors()); $result = false; }
Just testing code, not pretty but functional ;)