Drupal Form API & Adding Entity Form Fields

It seems my love for Drupal and its Form API is always expanding, yep, kinda creepy sounding but to a web geek such as myself, it's perfectly normal to love a CMS and its API's!

In building my custom form I required an entity field which is present on user creation. Instead of duplicating the field, grabbing the current value and then saving the new value with an user_save() it's best practice to let Drupal handle the heavy lifting, since we don't want to duplicate tried and tested functionality or have to update the custom field should anything change to the entity field.

Right-o, let's start by creating our form.

/**
 * My custom form.
 */
function deckfifty_form($form, &$form_state) {

	$form['submit'] = array(
	'#type' => 'submit',
	'#value' => 'Submit',
	);
	
	return $form;
}

Now that we have our basic (and really boring) form in place, we'll add our entity field.

/**
 * My custom form.
 */
function deckfifty_form($form, &$form_state) {
// get user object
global $user;
$user_obj = user_load($user->uid);

 // we need to add this empty array, or we will get an ugly error
	$form['#parents'] = array();

	// entity field
	$field = field_info_field('field_profile_subscription');
	$instance = field_info_instance('user', 'field_profile_subscription', 'user');
	$items = field_get_items('user', $user_obj, 'field_profile_subscription');
	
	// add to subscription array
	$form['subscription'] = field_default_form('user', $user_obj, $field, $instance, LANGUAGE_NONE, $items, $form, $form_state);
	$form['subscription']['field_profile_subscription']['und'][0]['value']['#required'] = TRUE;

	// submit
	$form['submit'] = array(
		'#type' => 'submit',
		'#value' => 'Submit',
	);
	
	return $form;
}

Finally we'll create a submit handler and save the new value in an user_save().

/**
 * Submit handler.
 */
function deckfifty_form_submit($form, &$form_state) {
	// get user object
	global $user;
	$user_obj = user_load($user->uid);

	//user save
	$edit = array(
	'field_profile_subscription' => $form_state['values']['field_profile_subscription'],
	'field_profile_zipcode' => $form_state['values']['field_profile_zipcode'],
	);
	user_save($user_obj, $edit);

	//set message
	drupal_set_message('Thank you! Your account has been updated!');
}

drupal entity form fields

Easy peasy right!? Have fun implementing this snippet in your next Drupal project!

Shane Graham

Shane Graham

Shane Graham is a senior Drupal developer and co-founder of Deck Fifty Design.

Get in touch

Let's go!

We look forward to hearing from you!