2

I'm having a hard time inserting new content into an elementselect field for a user.

Here's the code I'm working on so far, inside a custom plugin init()

parent::init();
craft()->on('entries.onBeforeSaveEntry', function(Event $event) {
    $entry = $event->params['entry'];
    $isNew = $event->params['isNewEntry'];

    if ($isNew) {
        $user = craft()->users->getUserById($entry['authorId']);

        $focusList = $user->getContent()->focusList;

        if (!is_array($focusList)) {
            $focusList = array();
        }
        array_push($focusList, $entry);
        $user->getContent()->focusList = $focusList;

        craft()->users->saveUser($user);

    }
});

I'm tring to add a "onBeforeSaveEntry" hook, that first checks if the entry is new.

If it is, add the entry to the authors "focusList" (an article field without limits)

But I can't get it to work. Any suggestions?


The error message I'm stuck with so far:

"CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails" is the error message I'm battling
1
  • Tried to change the hook to "entries.onSaveEntry", and the error message turns into "var_export does not handle circular references" – Ole Jun 7 '16 at 12:27
2

Sweet, solved it.

Changed the line

array_push($focusList, $entry);

to

array_push($focusList, $entry->id);

and it worked! :D



EDIT: NOPE, it did not fully work. This hook overwrites all the other entries, leaving only the most recent inside the list.

This code does work, without overwriting:

parent::init();
craft()->on('entries.onSaveEntry', function(Event $event) {
    $entry = $event->params['entry'];
    $isNew = $event->params['isNewEntry'];

    if ($isNew) {
        $user = craft()->users->getUserById($entry['authorId']);
        $focusList = $user->getFieldValue('focusList');
        $values = [];


        foreach ($focusList as $focusEntry) {
            array_push($values, $focusEntry->id);
        }

        array_push($values, $entry->id);


        $user->setContentFromPost(array(
            'focusList' => $values
         ));
        craft()->users->saveUser($user);
    }
});

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.