In my plugin, how do I save a relationship when creating a new entry? The example below works for all but the "quiz" relationship.

$triviaSet = craft()->entries->getEntryById($data['itemId']);
$entry = new EntryModel();
$entry->sectionId   = 3
$entry->typeId     = 2
$entry->authorId   = 1;
$entry->enabled    = true;
    'title' => 'My New Entry',
    'score' => $data['score'],
    'quiz' => $triviaSet
$success = craft()->entries->saveEntry($entry);

Relations fields can store multiple related values (even if you only have one item). Perhaps try to pass an array to the 'quiz' value:

'quiz' => array($data['itemId'])

Alternatively, if you are submitting all of your content, in the correct format, you can get rid of your $entry->getContent()->setAttributes line and use the setContentFromPost method.

All you need to pass to the setContentFromPost method is the name of the custom content fields array you are submitting to the content table. For example, if your fields above were structured as follows in your front-end form template (this is a bit simplified for your complex field types like relations, but as long as your submitting the right values this should work):

<input type="text" name="title" value="My New Entry"> 
<input type="text" name="fields[score]" value="101">
<input type="text" name="fields[quiz][]" value="101">

Note that in the input field name of quiz relations field we are passing an array: fields[quiz][].

You can then receive your submitted data and hand it off to the ContentModel tied to your EntryModel. Your title is handled slightly differently than your custom content as the title field is a default attribute of the ContentModel:

$entry->getContent()->title = craft()->request->getPost('title');

And your array of submitted custom content can be handed off silently to the setContentFromPost field by just passing it the name of all of the fields.


You don't even need to capture your post data using something like craft()->request->getPost('fields'), just passing the 'fields' value to the function does all the heavy lifting for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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