I need to POST a JSON to a URL with a webform on it and have the WebformHandler.

This is the alterForm of my WebformHandlerBase subclass

public function alterForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    $json_params = file_get_contents("php://input");
    $decoded_params = json_decode($json_params, true);
    if (strlen($json_params) > 0 && json_last_error() == JSON_ERROR_NONE) {
      if (array_key_exists('prepop', $decoded_params) && $decoded_params['prepop']) {
        $flattened_elements = &WebformFormHelper::flattenElements($form['elements']);

        // This works! It's a plain old text field
        $flattened_elements['i_am_text']['#value'] = $decoded_params['i_am_text'];

        // This does not work! It's a text field, but in a webform composite
        $flattened_elements['address']['#webform_composite_elements']['line_1']['#value'] = $decoded_params['line_1'];

I'm able to pre-populate a plain old text field, but an element in a webform composite is not co-operating.

I was also unable to get this the following working for either plain text boxes or composites:

$form_state->setValue('i_am_text', $decoded_params['i_am_text']);

I also tried using

$form_state->setUserInput(['i_am_text' => $decoded_params['i_am_text']]);


I found this in Drupal's docs:


This can be typically used to pre-fill entity values or change the form state before the entity form is built.

And the code example looks like the exact thing I want. So I tried the following code:

function evans_personal_hell_entity_prepare_form(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->set('i_am_text', 'This is ridiculous');
  $form_state->set('address', [
      'address_1' => 'I hate this',
      'address_2' => 'I hate this',
      'city' => 'I hate this',
      'province' => 'I hate this',
      'postal_code' => 'I hate this',
      'country' => 'I hate this'

It appears to do nothing? I know the code is triggered because I get a divided by zero warning in the logs if I add $crap = 0 / 0; to the end of the hook.

I must be missing something super obvious, because this now appears to be impossible.

Your Answer

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

Browse other questions tagged or ask your own question.