I have already developed a field widget that queries an API based on a value in a textfield and i want to now create a Webform element to do the same thing for poeple using Webform.
Because i need my element to have a textfield, a button to trigger the API request, and an HTML area to display the result, I am presuming i need to extend my class from WebformCompositeBase.
If I write the callback in the same way as I have done on my working field widget, as per below - I get "Error: Using $this when not in object context" error:
public static function getCompositeElements(array $element) {
$drupal_translation = \Drupal::translation();
$elements = [];
$elements['registration_number'] = [
'#type' => 'textfield',
'#title' => $drupal_translation->translate('Vehicle Registration Number'),
];
// Add a button for sending the API request.
$elements['api_button'] = [
'#type' => 'button',
'#value' => 'Check vehicle details',
'#ajax' => [
'callback' => [$this, 'sendApiRequest'],
'event' => 'click',
'wrapper' => 'api-response-wrapper', // The HTML ID where the API response will be displayed.
],
];
// Display area for API response.
$elements['api_response'] = [
'#type' => 'markup',
'#prefix' => '<div id="api-response-wrapper">',
'#suffix' => '</div>',
'#markup' => '',
];
return $elements;
}
If I write it like below I get a "The specified #ajax callback is empty or not callable" error.
'#ajax' => [
'callback' => 'sendApiRequest',
'event' => 'click',
'wrapper' => 'api-response-wrapper', // The HTML ID where the API response will be displayed.
],
The sendApiRequest function which is inside the class is as follows:
public function sendApiRequest(&$element, FormStateInterface $form_state, &$complete_form) {
\Drupal::messenger()->addMessage('API called');
}