How to auto-populate field based on the reference field

I have created a new portal type on my add on and I want it to have it so as when I provide the id for the object for that type the related fields are automatically filled or if it does not exist create it.