4

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 ;)

1 Answer 1

9

This should be as simple as setting the relation field (category, asset, etc.) value on the entry as an array of related element IDs before saving.

$entry->setFieldValue('categoryFieldHandle', [$categoryId1, $categoryId2]);

Craft::$app->elements->saveElement($entry);

This will work for all relation fields:

$entry->setFieldValue('assetFieldHandle', [$assetId1, $assetId2]);

Craft::$app->elements->saveElement($entry);
4
  • Oh no, just the ID slapinface I tried so many different versions, but just an array with ids.... so simple, great. So you have a hint for Image-Assets as well ? I think i will need a similar solution, but i am not able to create an image asset in my pluginservice ( not relate an existing one). And there is no tutorial or example, not in the official documentation, neither i found something useful in my google researches
    – Thomas
    Commented Nov 22, 2018 at 9:37
  • 1
    The same works for assets, added to my answer. For creating assets, please create a new question if you can't find an existing one on the site.
    – Ben Croker
    Commented Nov 22, 2018 at 14:09
  • Thanks a lot, you are absolutely right - i just finished my plugin function with your help. I hope more people will use the craft Vms so we will find more and more Tuts and questions/solutions in the future.
    – Thomas
    Commented Nov 24, 2018 at 9:31
  • Glad to hear it!
    – Ben Croker
    Commented Nov 24, 2018 at 13:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.