Automatically generate AccountLink field value

Hi all,

I have a form on the front end that collects data and creates a new backend account as well as a new entry under my ‘consumers’ collection.

Is there a way i can make the AccountLink field on my consumer collection to automatically link to the backend account by matching the account usernames? Instead of manualy selecting them from the fields option list?

Ive tried fetching the newly created account _id after creating, then posting to the new entry field but no luck.

Ive also tried to create an event but I think i’m missing a comparison to the Accounts ‘username’ field & not sure how to go about it:
(Not a PHP head)


<?php

// consumers is my collection name
// ass_consumer is my 'associated account' (AccountLink field)

$app->on('collections.save.after.consumers', function($name, &$entries) {

    foreach ($entries as &$entry) {

        if(isset($entry['ass_consumer'])){
            $account = $this->storage->findOne('cockpit/accounts', ['user' => $entry['username']]);
            $entry['ass_consumer'] = !empty($account['user']) ? $account['user'] : $account['user'];
        }

    }

});

Any help would be appreciated!

If I am not wrong, you are missing something here. I often try like this and it works.


fetch('https://example.com/api/collections/save/consumers?token=12345678901112131415', {
    method: 'post',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({data: {
      "ass_consumer": "_id of your newly created account",
     // the rest fields
      }})
})
.then(e => e.json())
.then(res => console.log(res));

Hey, i realised i was trying to change my react state before it had a chance to update since its asynchronous and it was returning undefined. sorted it now though