Search code examples
drupal-7

Copying and Concating Two Textfields to another in Drupal Webforms


I am having two Selects as Type and Category. The third is a textfield named Index. The values for Type is 1, 2, 3, 4, 5 and Category is A, B, C, D, E.

I would like to get automatically the value in Index as 4A or 1E as the case may be as selected by user.


Solution

  • Hey I tried out this and its working, You can do this using hook_form_alter, #after_build and jQuery.

    First of all create your webform with desired fields. Then create a custom module and use hook_form_alter, I am adding a sample code below, you just need to replace "hook" with your module name and "your_webform_id" with your webform id.

    function hook_form_alter(&$form, &$form_state, $form_id){
        //to check your webform id.
        //drupal_set_message($form_id);
    
        if($form_id == "your_webform_id"){
            $form['#after_build'] = array('_webform_after_build_handler');
        }
    }
    
    function _webform_after_build_handler(&$form, &$form_state){
        //*change the webform field id's as per your form*
    
        drupal_add_js('jQuery(document).ready(function(){ 
        var typ = jQuery("#edit-submitted-type").val();
        var cat = jQuery("#edit-submitted-category").val();
        if(cat != "" && typ != ""){
                jQuery("#edit-submitted-index").val(typ + cat);
            }
        jQuery("#edit-submitted-category").change(function(e){
            var typ = jQuery("#edit-submitted-type").val();
            var cat = jQuery(this).val();
            if(cat != "" && typ != ""){
                jQuery("#edit-submitted-index").val(typ + cat);
            }
        });
        jQuery("#edit-submitted-type").change(function(e){
            var typ = jQuery(this).val();
            var cat = jQuery("#edit-submitted-category").val();
            if(cat != "" && typ != ""){
                jQuery("#edit-submitted-index").val(typ + cat);
            }
        });', 'inline');
        return $form;
    }
    

    Hope this will help you.