Drupal: Programmatically Create Horizontal Tabs in a Custom Form

We happen to be in an engineering R&D sprint at work and I’m working on a widget maker so users can embed a small snippet into their blog and show off their latest reviews and so on. I’m working on the widget generator UI, which is a custom form that will call some JS on submit to output the desired markup. I wanted each widget type to be in its own horizontal tab, a la Twitter’s widget configurator (must be logged in to view. If this were a content type, it would be easy enough to group fields into a horizontal tabs group and child horizontal tabs, but the form is completely made from scratch. After much trial and error, here’s the minimum necessary to create horizontal tabs.

/**
 * Form callback.
 */
function csm_api_widget_form($form, &$form_state) {

  // Horizontal tabs container
  $form['group_tabs'] = array(
    '#type'     => 'horizontal_tabs',
    '#attached' => array('library' => array(array('field_group', 'horizontal-tabs'))), // Converts fieldsets into tabs
  );

  // My Reviews tab
  $form['group_user_reviews'] = array(
    '#type'  => 'fieldset',
    '#title' => t('My Reviews'),
    '#group' => 'group_tabs',
  );

  // Field - username (hardcoded)
  $form['group_user_reviews']['name'] =	array(
    '#type' => 'textfield',
    '#title' => t('My text field'),
    '#group' => 'group_user_reviews',
  );

  // Field - submit button
  $form['group_user_reviews']['submit'] = array(
    '#type'  => 'button',
    '#value' => t('Create My Reviews Widget'),
    '#group' => 'group_user_reviews',
  );

  // My Favorites tab
  $form['group_favorites'] = array(
    '#type'  => 'fieldset',
    '#title' => t('My Favorites'),
    '#group' => 'group_tabs',
  );

  $form['group_favorites']['submit'] = array(
    '#type'  => 'button',
    '#value' => t('Create My Favorites Widget'),
    '#group' => 'group_favorites',
  );

  return $form;
}