Score:0

How do I programatically change a webform's element type?

ng flag

I am using a webform element 'select_other' in the webform. We got a requirement that the Other field should only appear if certain conditions are satisfied. I already have a Webform Handler In place, and using the alterForm(), I tried to change the #type value, which removed the Other option, but duplicates the field wrapper property.

Is there any way to change the #type of a webform element programmatically from webform_select_other to select?

I was able to get around this by creating a dummy element for select and then in the alterForm, substituting the form element with the new one, using this code.

$type_of_request = $webform_submission->getElementData('type_of_request');

if ($type_of_request == "Process") {
  $webform = $webform_submission->getWebform();
  $dummy_element = $webform->getElement('dummy_element');
  $elements['original_element'] = $dummy_element;
  unset($elements['original_element']['#access']);
}

This is a workaround I am using.

id flag
What are the certain conditions that must be satisfied? It matters.
Score:0
nl flag

You should change it to always use a select element, and then make a separate textfield (or whatever type) field for "Other". Then you can use the Webform module's built-in conditionals to control when it shows, without using a webform handler for that.

  1. Add a select element
  2. Add a separate textfield "Other" element
  3. Add a "visible" conditional on the Other element, with the condition being that the type_of_request is set to Process

Example YAML

  type_of_request:
    '#type': select
    '#title': 'Type of Request'
    '#options':
       review: Review
       process: Process
    '#required': true
  select:
    '#type': select
    '#title': 'Select'
    '#options':
       - 'Option 1'
       - 'Option 2'
    '#required': true
  other:
    '#type': textfield
    '#title': 'Other'
    '#required': true
    '#states':
      visible:
        - ':input[name="type_of_request"]':
            value: process
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.