View source
<?php
namespace Drupal\filebrowser\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Cache\Cache;
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
class UploadForm extends FormBase {
protected $queryFid;
protected $relativeRoot;
protected $node;
protected $nid;
protected $common;
public function getFormId() {
return 'upload_form';
}
public function buildForm(array $form, FormStateInterface $form_state, $nid = null, $query_fid = null, $fids = null, $ajax = null) {
$this->common = \Drupal::service('filebrowser.common');
$this->relativeRoot = $this->common
->relativePath($query_fid);
$this->node = Node::load($nid);
$this->queryFid = $query_fid;
$this->nid = $nid;
$accepted = $this->node->filebrowser->accepted;
if ($ajax) {
$form['#attributes'] = [
'class' => [
'form-in-slide-down',
],
];
$form['close'] = $this->common
->closeButtonMarkup();
}
if ($this->node->filebrowser->folderPath && $this->relativeRoot) {
$upload_location = preg_replace('/\\/\\/$/', '/', $this->node->filebrowser->folderPath) . $this->relativeRoot;
}
else {
$upload_location = $this->node->filebrowser->folderPath . $this->relativeRoot;
}
$form['u_file'] = [
'#title' => $this
->t('Upload file'),
'#type' => 'filebrowser_managed_file',
'#description' => $this
->t('File types accepted: @accepted', [
'@accepted' => $accepted,
]) . '<br>' . $this
->t('You can upload multiple files.'),
'#upload_validators' => [
'file_validate_extensions' => [
$this->node->filebrowser->accepted,
],
],
'#upload_location' => $upload_location,
'#progress_indicator' => 'bar',
'#progress_message' => $this
->t('Please wait...'),
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Save Upload'),
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$file_ids = $form_state
->getValue('u_file');
if (count($file_ids)) {
$success = \Drupal::service('filebrowser.storage')
->genericDeleteMultiple('file_managed', 'fid', join(',', $file_ids));
if ($success) {
\Drupal::messenger()
->addMessage($this
->t("Your filebrowser upload is completed successfully!"));
}
else {
\Drupal::messenger()
->addError($this
->t('Your upload completed successfully, but file_managed clean-up failed'));
}
}
Cache::invalidateTags([
'filebrowser:node:' . $this->nid,
]);
$route = $this->common
->redirectRoute($this->queryFid, $this->node
->id());
$form_state
->setRedirect($route['name'], $route['node'], $route['query']);
}
}