You are here

public function ImageBrowserController::update in Image Entity Browser 8

Reload widget to with new value assign in javascript

1 string reference to 'ImageBrowserController::update'
image_browser.routing.yml in ./image_browser.routing.yml
image_browser.routing.yml

File

src/Controller/ImageBrowserController.php, line 50

Class

ImageBrowserController

Namespace

Drupal\image_browser\Controller

Code

public function update() {
  $response = new AjaxResponse();
  $fid = 0;
  $file = \Drupal::request()
    ->get('file');
  $selector = \Drupal::request()
    ->get('selector');
  $fid = str_replace('file:', '', $file);
  if ($fid) {
    $file = File::load($fid);
    $file_url = file_create_url($file
      ->getFileUri());
    if ($file
      ->getMimeType() == 'image/svg+xml') {
      $preview = array(
        '#markup' => '<img src="' . $file_url . '"/>',
      );
    }
    else {
      $preview = array(
        '#theme' => 'image_style',
        '#style_name' => 'image_browser_thumbnail',
        '#uri' => $file
          ->getFileUri(),
      );
    }
    $response
      ->addCommand(new HtmlCommand($selector . ' .image-preview', $preview));
    $response
      ->addCommand(new InvokeCommand($selector . ' input[type=hidden]', 'val', array(
      'file:' . $fid,
    )));
    $response
      ->addCommand(new InvokeCommand($selector, 'addClass', array(
      'has-image',
    )));
    $response
      ->addCommand(new InvokeCommand($selector . ' input[type=hidden]', 'data', array(
      [
        'url' => $file_url,
      ],
    )));
    $response
      ->addCommand(new InvokeCommand($selector . ' input[type=hidden]', 'trigger', array(
      'update',
    )));
  }
  else {
    $response
      ->addCommand(new HtmlCommand($selector . ' .image-preview', ''));
    $response
      ->addCommand(new InvokeCommand($selector . ' input[type=hidden]', 'val', array(
      '',
    )));
    $response
      ->addCommand(new InvokeCommand($selector, 'removeClass', array(
      'has-image',
    )));
    $response
      ->addCommand(new InvokeCommand($selector . ' input[type=hidden]', 'trigger', array(
      'update',
    )));
  }
  return $response;
}