I have a webform field called company name and i want that when the webform is opened it has a prepopulated value i want to do it from code because i will have a dynamic variable. THis is the code i am using.(currently it is not working a the filed is staying empty

enter image description here

use Drupal\Core\Form\FormStateInterface;

function investigation_export_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    // Log the form ID being altered.
    \Drupal::logger('investigation_export')->notice('Altering form with ID: @form_id', ['@form_id' => $form_id]);

    // Check if we are dealing with the correct webform.
    if ($form_id === 'webform_submission_investigation_add_form') {
        // Log that the correct webform is being processed.
        \Drupal::logger('investigation_export')->notice('Processing webform with ID: @form_id', ['@form_id' => $form_id]);
        // if you want to conditionally prepopulate the field based on the form's current page.
        $current_page = $form_state->get('current_page');
        if (isset($form['elements']['company_name_mbr'])) {
            // Log that the field exists.
            \Drupal::logger('investigation_export')->notice('Field company_name_mbr found in form.');

            // Prepopulate the 'letterforsubmission' field with "hello".
            $form['elements']['company_name_mbr']['#default_value'] = 'hello';

            // Log that the field has been prepopulated.
            \Drupal::logger('investigation_export')->notice('Prepopulating field company_name_mbr with "hello".');
        } }



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.