Programmatically populate a Drupal form I am very new to Drupal and trying to write a module. I have 2 entities - Membership and MembershipRequest and both are fieldable. A MembershipRequest is a request to the admin of the website to create or update (renew/delete) a Membership entity. On the MembeshipRequest form, I want to populate the form elements with Membership entity values that user are requesting to update. For example, on the request form's First name text box, I want to populate the Membership's First name. I have membership_id property in the the request entity. But the First name and other fields are attached to both entities via Field API. 

I am not sure which object (and how) - $form, $form_state, $request - I need to modify so that the request form will show up with populated values.

Thanks a lot.
If you insist on programming this, and not use and configure contrib modules - 

If fields were added to entity bundle via drupal admin UI

You can use hook_form_alter() or hook_form_FORM_ID_alter, and in the code there have the particular field populated with desired default value.


hook_form_alter() would be invoked for all forms and you would have to have an if condition to target just the desired form id.
hook_form_FORM_ID_alter() would be invoked for particular form.


If field was attached using Field API code (not the case for this question)

You would have an implementation of hook_field_attach_form() to attach fields to your MembeshipRequest entity. It would be in that hook implementation that you would set a #default_value to the desired form field. 

Code to use in either of the cases above

$form['foo']['bar'] = array(
  '#type' =&gt; 'textfield', 
  '#title' =&gt; t('foobar'), 
  '#default_value' =&gt; _func_to_get_default_value($member_id), 
  '#description' =&gt; t('something something'),
  '#size' =&gt; 60, 
);  
// NOTE: Replace foo/bar with the particular field etc.