1

I have a webform created using interface, and need to hide some fields through button. Using form_alter I have added that button added AJAX call with it. Now I want to remove/hide certain element using that button and AJAX.

Below is the sample code

function xyz_user_signup_form_webform_submission_form1_form_alter(array &$form, FormStateInterface $form_state, $form_id) {


  $form['#attached']['library'][] = 'xyz/xyz.global';

  $form['start'] = [
      '#type' => 'button',

      '#ajax' => [
        'callback' => 'xyz_user_signup',
       ],
      '#value' => t('START >>'),
  ];

}

function xyz_user_signup(array &$form, FormStateInterface $form_state) {

    $elements = &WebformFormHelper::flattenElements($form['elements']);


    $elements['field1']['#access'] = FALSE;


    return $elements;
}

On clicking start button I want to hide field1.

2
  • Please share your inputs how about sharing your alter code... otherwise we would have to be psychics.
    – No Sssweat
    Oct 31, 2019 at 8:21
  • Sure let me edit the issue
    – parth.k
    Oct 31, 2019 at 8:22

1 Answer 1

2

Your AJAX needs to have a target ID where it will put your AJAX output. You declare that ID in the wrapper key.

In your form_alter

  '#ajax' => [
    'callback' => 'xyz_user_signup',
    'wrapper' => 'load-me-here-id', // This element is updated with this AJAX callback.
   ],

Then you need to wrap the field with this ID so AJAX replaces it.

 $form['elements']['field1']['#attributes'] = ['id' => 'load-me-here-id'];

In your ajax callback

return $elements['field1']; // so it doesn't return the entire form.
3
  • I implement as per your suggestion, but in ajax callback my code is to set #access property to FALSE of a fieldset element which is not working yet.
    – parth.k
    Oct 31, 2019 at 10:04
  • @parth.k Make sure your ajax is indeed working. For testing purposes, put return 'Hello World'; you should see that "hello world", if not then AJAX it is still not working like it's suppose to.
    – No Sssweat
    Oct 31, 2019 at 11:15
  • @parth.k updated my answer, forgot to add elements to the attributes array.
    – No Sssweat
    Oct 31, 2019 at 11:29

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.