<p>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.</p>
<pre><code>$entry-&gt;setFieldValue('categoryFieldHandle', [$categoryId1, $categoryId2]);

Craft::$app-&gt;elements-&gt;saveElement($entry);
</code></pre>
<p>This will work for all relation fields:</p>
<pre><code>$entry-&gt;setFieldValue('assetFieldHandle', [$assetId1, $assetId2]);

Craft::$app-&gt;elements-&gt;saveElement($entry);
</code></pre>

CC BY-SA 4.0
2018-11-22T09:37:12.637Z
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
CC BY-SA 4.0
2018-11-22T14:09:36.977Z
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
CC BY-SA 4.0
2018-11-24T09:31:07.707Z
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
CC BY-SA 4.0
2018-11-24T13:16:13.750Z
Glad to hear it!
Ben Croker
CC BY-SA 4.0
2018-11-21T08:35:03.850Z
2021-05-18T21:33:21.137Z
2021-05-18T21:33:21.137Z
Ben Croker
<p>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 :)</p>

<p>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 <a href="https://craftcms.stackexchange.com/questions/16209/saverelations-returning-null">Problem/Example</a> into my version in craft 3. No success :(</p>

<p>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 ?</p>

<p>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 ?</p>

<pre>
    $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;
    }
</pre>

<p>Just testing code, not pretty but functional ;)</p>

<plugin-development><craft3><assets><relations><saveentry>
Craft 3 - Save new Entry with Relations (Categories/Assets)
# Craft 3 - Save new Entry with Relations (Categories/Assets)

(Asked by: username_0 on 2018-11-19)

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

**Tags:** plugin-development, craft3, assets, relations, saveentry


---

## 1 answers

### Answer by username_1 on 2018-11-21. Score: 9 | Accepted answer

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

> **Comments:**
> **username_0**: 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  
> **username_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.  
> **username_0**: 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.  
> **username_1**: Glad to hear it!  

---

