2

I'm trying to add an ajax callback in a FieldWidget. I definied my element:

$element['value']['#ajax'] = [
  'callback' => [$this, 'ajaxRefreshField'],
];

Next in my callback, how do I access the form_state value filled out in the field and the element defined on the form?

    public function ajaxRefreshField(array $form, FormStateInterface $form_state, Request $request) { 
      // What I want to do is something like this:
      $response = new AjaxResponse();
      $element = $form->get-my-element-in-some-sort-of-way
      $element['add-a-change'] = [...];
      $response->addCommand(new ReplaceCommand('my-selector', $element));

      return $response;
    }
3
  • Do you mean $form_state->getValue('foo');?
    – Clive
    Mar 31, 2017 at 11:50
  • Yeah, but the form_state is a tree and it is possible my field is configured for example on a Paragraph... so I then I have to fetch the element from the paragraph definied on the form... I want to find a dynamic way to do this
    – Robin
    Mar 31, 2017 at 12:30
  • Or if other contrib modules have ajax calls in their FieldWidget, I would be glad to check them, but I don't know of any...
    – Robin
    Mar 31, 2017 at 12:31

1 Answer 1

1

Grab the triggering element from the $form_state in your AJAX callback method:

$triggeringElement = $form_state->getTriggeringElement();
$value = $triggeringElement['#value'];

Your Answer

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

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