DataCommand example

/** * Simple object for testing methods as Ajax callbacks. */
class Callbacks {

  /** * Ajax callback triggered by select. */
  public function selectCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax_selected_color', $form_state->getValue('select')));
    $response->addCommand(new DataCommand('#ajax_selected_color', 'form_state_value_select', $form_state->getValue('select')));
    return $response;
  }

  /** * Ajax callback triggered by date. */
  public function dateCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $date = $form_state->getValue('date');
    $response->addCommand(new HtmlCommand('#ajax_date_value', sprintf('<div>%s</div>', $date)));
    $response->addCommand(new DataCommand('#ajax_date_value', 'form_state_value_date', $form_state->getValue('date')));
    
'font-weight' => 'bold',
      ],
    ];

    $this->assertEquals($expected$command->render());
  }

  /** * @covers \Drupal\Core\Ajax\DataCommand */
  public function testDataCommand() {
    $command = new DataCommand('#page-title', 'my-data', ['key' => 'value']);

    $expected = [
      'command' => 'data',
      'selector' => '#page-title',
      'name' => 'my-data',
      'value' => ['key' => 'value'],
    ];

    $this->assertEquals($expected$command->render());
  }

  
Home | Imprint | This part of the site doesn't use cookies.