Automatically add a field to every new webform created

Posted on: October 30th, 2013 by admin 1 Comment

I recently had a need for users to be able to attach webforms to some node types to allow users to give feedback.

Each webform could be attached to multiple nodes.

When the webform data was submitted it needed to record which node it was attached to.

This was easy enough by adding a hidden field with the default value of %get[q] to record the nid.

However I didn’t want users to have to do this manually every time a webform was created, instead I wanted this field to be automatically included on every new webform added.

To do this I needed to act on the webform node after it had been inserted into the database so hook_node_submit was out of the question.

Instead I added an additional submit function on the webform_node_form to fire after the node module and webform module had finished doing their bit:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
	if($form_id=='webform_node_form') $form['actions']['submit']['#submit'][] = 'misc_webform_form_submit';
)

Now in the new submit handler we simply add the new field to the webform and save the node (which is why the node had to be already created).

function misc_webform_form_submit($form, &$form_state) {
 
	$node = node_load($form_state['build_info']['args'][0]->nid);
	$node->webform['components'][] = array(
		'nid' => $node->nid,
		'cid' => 1,
		'pid' => 0,
		'form_key' => 'related_document',
		'name' => 'Related Document',
		'type' => 'hidden',
		'value' => '%get[q]',
		'extra' => array(
			'hidden_type' => 'value',
			'conditional_operator' => '=',
			'private' => 0,
			'conditional_component' => '',
			'conditional_values' => ''
		),
		'mandatory' => 0,
		'weight' => 0,
		'page_num' => 1
	);
	node_save($node);
}