0

I am trying to update the value of an Entries field on an EntryModel, however I am having a lot of trouble getting it to update correctly.

I've tried allocating both an entire EntryModel and its id but neither seems to set the value, e.g.

$comment = new EntryModel();
$comment->sectionId = $commentSectionId;

$comment->setContent(array(
    'createdBy' => $user // or
    'createdBy' => $user->id
));

craft()->entries->saveEntry($comment);

Where $user is a valid EntryModel.

The comment saves fine, the createdBy field just has no value. I guess I am using the wrong data from $user but I have having a very hard time finding any thorough documentation around setting different kinds of EntryModel data.

This is the entire bit of code I have, if it helps:

class Bugr_CommentService extends BaseApplicationComponent
{

    public function post(EntryModel $user, EntryModel $ticket, $body)
    {
        $comment = new EntryModel();
        $comment->sectionId = craft()->sections->getSectionByHandle('comments')->id;

        $comment->setContent(array(
            'createdBy' => $user,
            'ticket' => $ticket,
            'body' => $body
        ));

        return craft()->entries->saveEntry($comment);
    }

}
  • Need to set the user id within an array. 'createdBy'=>array($user->id) or 'createdBy'=>[$user->id]. Very similar question can be found here. – Douglas McDonald May 8 '15 at 0:52
  • @DouglasMcDonald Ohh of course, because the entries field is obviously a list of entries. Sigh, makes perfect sense - thank you. – Marty May 8 '15 at 0:53
  • Should also be using getContent()->setAttributes([...]) (or setContentFromPost() if coming from post data) instead of setContent(). Check out the example I linked. – Douglas McDonald May 8 '15 at 0:58
  • @DouglasMcDonald Sure, I'll keep that in mind. This is pretty much a duplicate but it would be nice if there was a more generic thread that covers both this and the linked questions. – Marty May 8 '15 at 1:02
  • Btw... I assume that 'createdBy' is a custom field? To set the author you would obviously want to use $entry->authorId = 1; where 1 is the id of the user/author. – Douglas McDonald May 8 '15 at 1:06
1

To assign a related Element (i.e. related User, Category, Entry, Tag, Asset) the value should be set to an array of element ids (even if there is only one element).

public function post(UserModel $user, EntryModel $ticket, $body)
{
    $comment = new EntryModel();
    $comment->sectionId = craft()->sections->getSectionByHandle('comments')->id;

    $comment->setContent(array(
        'createdBy' => array($user->id),
        'ticket'    => array($ticket->id),
        'body'      => $body
    ));

    return craft()->entries->saveEntry($comment);
}
| improve this answer | |

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.