2

Ok, I'm building a custom module that has content type that is webform enabled. When creating a node of this type, I need to automatically create one webform select field when node gets saved. How can I achieve this? The goal is that all webforms have this field when they're created, rest are user created.

2

I am not sure about your use case.

But the following module does exactly that.

Webform Default Fields

With this module you can easily create much of nodes with same webform fields. It can be applicable in case of job vacancies with reply form, kind of quality feedback control or whatever your mind suggests you.

Because you can create more than one webform-enabled content types, you respectively can attach different default fields for each of them.

  • solved using HOOK_node_insert(); – Tuomas Leppänen Feb 4 '13 at 9:06
  • This module works like a charm for me. Many thanks! – Roger Jun 5 '15 at 10:30
1
/** 
  * Implements hook_node_insert().
  */
function wf_queue_node_insert($node) {
  // Here we will force signup action field (and possibly other fields) that is default for all forms when they're created. When user adds component to the webform, select element for action to take is generated.
  if($node->type == "event") {
    // Include webform component functions. If we don't do this, we can't use webform functions needed to create element.
    module_load_include('inc', 'webform', 'includes/webform.components');

    // Check if field exists by doing database query and checking for cid = 99 on this node. TODO: This check is maybe too failsafe.
    $dbresultwf = db_query("SELECT * FROM {webform_component} WHERE nid = :nid AND cid = :cid", array(":nid" => $node->nid, ":cid" => 99))->fetchField();

    // It doesn't exists, create it.
    if(!$dbresultwf) {
      $component = array(
        // We set cid to 99 so it wont interfere with other components (This might need to be increased further for very complex forms. Does webform check for existing cid? If so we are fine.
        'cid' => 99,
        'pid' => 0,
        'nid' => (int)$node->nid,
        // Set machine name and display name
        'form_key' => 'event_action',
        'name' => t('Select an action'),
        // Type we need is a select options
        'type' => 'select',
        'extra' => array(
          'description' => 'Select an action to perform',
          'items' => 'signup|Signup' . "\n" . 'queue|Queue' . "\n" . 'cancel|Cancel',
        ),
        // This needs to be mandatory as it will be used for other functionality.
        'mandatory' => 1,
        'weight' => -99,
        'page_num' => 1,
        );
      // Insert component to webform
      webform_component_insert($component);
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.