Changing The Default Value Of A Form Field In Your Custom Drupal 7 Module

3 years 6 months ago

I guess I couldnt stay in the dark about hooks forever.  They are actually quite useful.  Here was my problem:

I am using a custom profile type for a drupal commerce site in drupal 7.  It is a simple profile type with one simple text field called "From Name".  All I wanted to do was have this be prepopulated with the default value from their last order.  

This was hard to find a module for.  Commerce Address Books is awesome, and I am using it for my billing address, but it is specifically for addresses.  So, after alot of trial and error I found out I needed to alter the form.  So, i added a function in my custom module "goodycerts" called goodycerts_form_alter.

function goodycerts_form_alter(&$form, &$form_state, $form_id) {
    $default = "Sup Bro";
    if ($form_id=='commerce_checkout_form_checkout') {
    //get last from name using whatever method you want

    $form['customer_profile_sender_inform']['field_from_name']['und'][0]['value']['#default_value'] = $default;
    }
}

I definitely needed to clear the cache before this started working.  It also took alot of work to figure out how to select that field.  Drupal 7 adds more selectors than Drupal 6 and most of the stuff out there is related to 6.

Its exciting to level up on my Drupal knowledge with this.  I feel like I am only a few levels away from creating my own modules for the Drupal community.