Callback after record is created that can be used to update another column
Callback after record is created that can be used to update another column
I'm using editor and node.js.
Is there a callback after I create a record that can be used to update another column with a value created in the first step?
More precise, if I create a record column 'id' is the auto increment and I want to update column 'invoice_id' with the value 'id'
.fields(
new Field( 'id' ),
new Field( 'invoice_id' ),
new Field( 'name' ),
)
.on( 'writeCreate', (editor, id, values) => {
console.log('id');
console.log(id);
console.log('values');
console.log(values);
editor
.field( 'invoice_id' )
.setValue( id );
})
console:
id
3
values
{ invoice_id: '' ,
name: 'Invoice' }
... so column invoice_id should be also 3
How can I do this?
This discussion has been closed.
Answers
Since you only have the id AFTER writing to the database you can't use a simple setFormatter in this case, or - as you tried - "setValue" which doesn't make sense in the "writeCreate" event handler because it is too late to manipulate Editor at this point in time.
What you can do is make a manual update of invoice_id using the "writeCreate" event handler. Either by using the raw() method or other methods of Editor's db handler (see the docs for those) or by using your own db handler. Can't give you an example because I don't use node.js.
But the question is: Why do you need invoice_id if it is apparently identical with id? This kind of redundance is usually only good for nothing but trouble ...
Here is an example of the raw() method in PHP. You might be able to adapt this or find something in the docs:
This is not very elegant. I would really think about your database design. Why do you need an invoice_id which is identical with the (auto increment) id of your table? Just use the id as the invoice_id!
Another option if you want to keep invoice_id is to set a database trigger that fills invoice_id with id after create. Then you don't need to code anything.