This part of my custom form depends on ajax to conditionally show additional fields. It is working.
$form['which_dataset'] = [
'#type' => 'select',
'#title' => $this->t('Which dataset are you requesting?'),
'#required' => TRUE,
'#options' => $dataset_options,
'#ajax' => [
'wrapper' => 'wrapper',
'event' => 'change',
'callback' => '::my_callback'
],
];
public function my_callback($form, $form_state){
return $form['allowed'];
}Now the customer wants a Drupal.dialog if the user selected an arbitrary option in this select field. OK, I have a callback that is invoked so I ought to be able to add more logic to it if the dialog should appear.
It's been suggested to use Javascript for this, but the AJAX, and the JS, would be using the change event. After many fruitless attempts, I'm hoping that invoking addCommands() should do the trick based on my reading of the docs.
use \Drupal\Core\Ajax\OpenDialogCommand
use Drupal\Core\Ajax\AjaxResponse;
public function my_callback($form, $form_state){
if($mylogic == TRUE) {
$response = new AjaxResponse();
$selector = 'div#cs2'; //set outside the $form['allowed']
$title = 'Notice:';
$content = "Hello, world";
$dialog_options = ['minHeight' => 100, 'resizable' => TRUE];
$options = [];
$response->addCommand(new OpenDialogCommand($selector, $title, $content, $dialog_options, $options));
}
return $form['allowed'];
}Setting a breakpoint and watching it go through the AjaxRendering process I see the Command is saved but the rendered output is the $form['allowed']. So I'm clearly not reading the docs right and am hoping someone can point me to how the addCommand() should be implemented.
PS: nearly all Drupal docs suggest using Drupal.dialog with a url as its source. I just want to know how to pass "Hello, world" to a dialog box.
Comments
If you invoke an AJAX Command
If you invoke an AJAX Command, you have to return an AjaxResponse object instead. Replace this string:
with this:
See AJAX Forms.
Re: Two things at once ...
Thx @wombatbuddy as that is the right answer.
That gets one thing done and digging into the linked Form wiki I can see that I would need to refer back to the #ajax selector in a second addCommand() like so:
The ReplaceCommand acts as the original callback to the $form object (inside the callback function).