How to pre-populate fields on a node creation form based on fields from Profile2 module?
There is a content type ("Job Listing") that a business account can use to list job openings, and a Profile2 profile for each business that contains the business's address, organization name and taxonomy terms such as industry type.
95% of the businesses that will list a job posting will use the same information; I could just use the profile information, but I need to account for the 5% that might want to change the job listing form. For example, the job might be in another state or country and that needs to be accounted for. I think the the best way to handle this situation is to have the same fields in both the profile and job listing form but allow the business change the information in the job listing form.
It would make sense to pre-populate the job listing form with business profile information as the default. How do I best do this? I was going to use Rules but I can't find a single option for a Rule before the original node creation form is created.
Should I just use
hook_form_alter() to access the profile information on orginal node creation and use that information to set the default values?
I created a hook_form_FORM_ID_alter() function in a helper module that tests to see if the node has a NID and if so if it is not in the operation preview. Then I populate the default values of the form with the companies profile information so they can change it later.
I had the same requirement and used the code above to get started. Unfortunately the code above does not take multiple country selections and therefore the dynamic field nature of country specific fields (provinces, states, etc.) into account. I cobbled together a new function to pre-populate the address field but with the ability to switch to the right country.
I got that snippet of code on how to do this from mrfelton who wrote a patch for similar address population functionality for drupal commerce. Thanks for that inspiration.
So here is my function that I used to pre-fill field address data. Please improve on this and give back to the community.
I made a more generic (but not perfect) module based on the answer from endless summer. It assumes that the field names from your profile and the node are the same and will prepopulate all fields from a given profile: