Record duplication from a custom widget

Just to clarify, this question is different from my previous one:

In that case I started using a formula column to obtain the ids of children records, and duplicate them.

This time I would like to code a generic record duplication function.