Use IMCE files browser for custom field on Drupal 8/9 | Drupal 8

Use IMCE files browser for custom field on Drupal 8/9

Submitted by editor on Fri, 12/04/2020 - 11:34

You can use IMCE to select a file.

if (\Drupal::moduleHandler()->moduleExists('imce') && \Drupal\imce\Imce::access()) {
  $form['values']['image-imce-field'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Image'),
    '#attached' => ['library' => ['imce/drupal.imce.input']],
    '#attributes' => ['class' => ['imce-url-input']],
    '#default_value' => '',
  ];
}

Convert file path to FID

public static function getFidFromPath($path) {
  $uri = str_replace('/sites/default/files/', 'public://', $path);
  $query = \Drupal::entityQuery('file');
  $query->condition('uri', $uri);
  $query->sort('created', 'DESC');
  $fids = $query->execute();
  if ($fids) {
    $fids = array_values($fids);
    return $fids[0] ??  NULL;
  }
  return NULL;
}

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.