1

In a custom submit handler, I want to set a field value for a text field (my_field_machinename) in my webform. The handler is getting called correctly, but the value is not getting stored. What do I have to change in the code below to make it work?

I know I could use the presave hook, but I would prefer to make the alteration within the submit handler.

class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($form_state);
  }

  /**
   * Set my field values
   */
  private function submitMyFieldData(FormStateInterface $formState) {
    $formState->setValue('my_field_machinename', [['value' => '123']]); // Does not work

  }

}

4
  • I see a space there in $this-> submitMyFieldData fix this and retry. Then please update your question and a little bit of detail what exact field you are referring to. You want to hardcode a value in the webform submission? Or is this a node field? What are you trying to achieve and why?
    – leymannx
    May 19 at 16:22
  • Thanks for the hint! Problem persists even without the space. I do not want to hardcode anything. The above is just an example of how I am trying to set the value. All my code is working, just the last bit when I try to set the value does not work, which is why I have focussed on this in the example above.
    – Extect
    May 19 at 16:32
  • I know webform is sometimes different but usually you'd add $form_state->setRebuild(); in submitForm
    – Clive
    May 19 at 18:32
  • Thanks @Clive! I tried that, but my values still do not get saved. Really strange. I don't get what I am doing wrong here.
    – Extect
    May 19 at 20:03
1

Only now did I realize there is not only a submitForm method but also a presave method. I therefore changed my code as follows which is woking fine for me:

class CustomHandler extends WebformHandlerBase {

  use StringTranslationTrait;


  /**
   * {@inheritdoc}
   */
  public function preSave(WebformSubmissionInterface $webform_submission) {
    $this->submitMyFieldData($webform_submission);
  }


  /**
   * @param $webform_submission
   *
   * Manipulate data.
   *
   */
  private function submitMyFieldData($webform_submission) {
    $data = $webform_submission->getData();

    // to get a value from a form field
    $form_value = $data['my_field_machinename'];

    // to set the value of a form field
    $data['my_field_machinename'] = $form_value + 1;

    $webform_submission->setData($data);

  }

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.