trinion_zadachnik-1.0.x-dev/src/Form/FileUploadForm.php

src/Form/FileUploadForm.php
<?php

namespace Drupal\trinion_zadachnik\Form;

use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a file upload form.
 */
class FileUploadForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'trinion_zadachnik_file_upload';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attributes']['class'][] = 'hidden';
    $form['file'] = [
      '#type' => 'file',
      '#required' => TRUE,
      '#attributes' => array('onchange' => 'jQuery("#trinion-zadachnik-file-upload").submit();'),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Загрузить',
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $all_files = $this->getRequest()->files->get('files', []);
    $file = $all_files['file'];
    $file_path = $file->getRealPath();
    $file_name = $file->getClientOriginalName();
    $file_repository = \Drupal::service('file.repository');
    $file_system = \Drupal::service('file_system');
    $dir = "private://" . date('Y-m');
    $file_system->prepareDirectory($dir, FileSystemInterface:: CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
    $file_name = $dir . "/" . $file_name;
    $file = $file_repository->writeData(file_get_contents($file_path), $file_name, FileSystemInterface::EXISTS_RENAME);
    $node->field_tz_file[] = $file->id();
    $node->save();
    $this->messenger()->addStatus('Файл прикреплен.');
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc