Good afternoon,

I am trying to upload a file by managed_file.

The source code is like below.

$form['photo'] = array(
            '#type' => 'managed_file',
            '#upload_location' => 'public://upload/teacher/photo'
          );

And I want to update the photo realtime which I don't know how to.

Once you select a file, the file will be automatically uploaded into server.

I want to get the event handlers of javascript. so I can show the uploaded image.

I am trying to do something like below and I know it's not right way.

$("#edit-photo-upload").change(function() {

I searched internet a lot to find some answers, but I cannot.

I want to know how to

- delete the record of managed_file when the file is removed from webbrowser.
- update/show uploaded file data in real time.
- show progresss bar
- upload multi-files

Please give me tip if someone knows about it.

Thank you.

Comments

slewazimuth’s picture

From the local_image plugin of the Drupal 8 Advanced Tour. However, this was from last March and its likely to have changed.

<?php
// Use the #managed_file FAPI element to upload an image file.
	$form['imagearray'] = array(
	'#title' => t('Local Computer Image'),
	'#type' => 'managed_file',
	'#description' => t('The uploaded image will be displayed on this page using the image style chosen below.'),
	'#default_value' => $this->get('imagearray'),
	'#upload_location' => 'public://images/',
	'#required' => FALSE,
	'#theme'	=>	'advimagearray_thumb_upload',
	);

...
.
.
.
...

/**
   * Overrides \Drupal\advancedtour\Plugin\advancedtour\advancedtour\TipPluginInterface::getOutput().
   */
   
  public function getOutput() {
    global $base_url;
	$imageid = $this->get('imagearray');
	$file = file_load($imageid[0]);
    $output = '<h2 class="advancedtour-tip-label" id="advancedtour-tip-' . $this->get('ariaId') . '-label">' . check_plain($this->get('label')) . '</h2>';
	$output .= '<p class="advancedtour-tip-image" id="advancedtour-tip-' . $this->get('ariaId') . '-contents">' . '<img src="' . $base_url . '/sites/default/files/images/' . $file->getFilename() . '" alt="' . $this->get('alt') . '" /></p>';
	
	return array('#markup' => $output);
  }
  
?>
Oualid-EZR’s picture

hi slewazimuth
im using you code for upload a image but i have thes error "Fatal error: Call to a member function getFilename() on null" and the result of var_dump($imageid); the result is NULL i dont now whay
myclass

/**
 * @file
 * Contains \Drupal\new_block\Plugin\Block\NewBlock.
 */

namespace Drupal\new_block\Plugin\Block;

 use Drupal\Core\Block\BlockBase; 
 use Drupal\Core\Form\FormBuilderInterface; 
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\Core\File\File;
/**
 * Provides a 'Newblock' block.
 *
 * @Block(
 *   id = "new_block",
 *   admin_label = @Translation("New  block"),
 *   category = @Translation("nouveauBlock")
 * )
 */
 class NewBlock extends BlockBase { 
 
 
 /** 
 * {@inheritdoc} 
 */ 
 public function build() { 
 
 $config = $this->getConfiguration(); 
     $title = isset($config['title']) ? $config['title'] : ''; 
     $photo = $this->getOutput();
     $description = isset($config['description']) ? $config['description'] : ''; 
 return array( 
   '#markup' => $this->t('<label>@title</label> <div>@photo</div> <p>@description</p>', array(
   	'@title' => $title,
   	'@photo' => $photo,
   	'@description' => $description
   	)), 
 ); 
 } 
 	public function get($attribut)
    {
        return $this->$attribut;
    }
 
 
 /** 
  * {@inheritdoc} 
  */ 
 public function blockForm($form, FormStateInterface $form_state) { 
	$form = parent::blockForm($form, $form_state); 

	$config = $this->getConfiguration(); 

	$form['title'] = array( '#type' => 'textfield', '#title' => t('Titre'), '#default_value' => isset($config['title']) ? $config['title'] : '',);
	$form['photo'] = array(
	    '#title' => t('Local Computer Image'),
	    '#type' => 'managed_file',
	    '#description' => t('The uploaded image will be displayed on this page using the image style chosen below.'),
	    '#default_value' => $this->get('photo'),
	    '#upload_location' => 'public://images/',
	    '#required' => FALSE,
	    '#theme'    =>    'advphoto_thumb_upload',
    );
	$form['description'] = array( '#type' => 'textarea', '#title' => t('Description'), '#default_value' => isset($config['description']) ? $config['description'] : '',);
	return $form; 
 } 
 
 /** 
  * {@inheritdoc} 
  */ 
 public function blockSubmit($form, FormStateInterface $form_state) { 
     // Save our custom settings when the form is submitted. 
   $this->setConfigurationValue('title', $form_state->getValue('title'));
   $this->setConfigurationValue('photo', $form_state->getValue('photo'));
   $this->setConfigurationValue('description', $form_state->getValue('description'));
 } 
 /**
   * Overrides \Drupal\advancedtour\Plugin\advancedtour\advancedtour\TipPluginInterface::getOutput().
   */
   
  public function getOutput() {
    global $base_url;
    $imageid = $this->get('photo');
    $file = file_load($imageid[1]);
    //var_dump($imageid); die();
    $output = '<h2 class="advancedtour-tip-label" id="advancedtour-tip-' . $this->get('ariaId') . '-label">' . $this->get('label') . '</h2>';
    $output .= '<p class="advancedtour-tip-image" id="advancedtour-tip-' . $this->get('ariaId') . '-contents">' . '<img src="' . $base_url . '/sites/default/files/images/' . $file->getFilename() . '" alt="' . $this->get('alt') . '" /></p>';
    
    return array('#photos' => $output);
  }

 } 

the image has uploded in sites\default\files\images
and $imageid return NULL too
Thank you.

slewazimuth’s picture

That code is very old and no longer being used. Uploading is now happening inside specific plugins.

Here's a snippet of something more recent.

	
	// Use the #managed_file FAPI element to upload an image file and signal
	// to render a thumbnail since this isn't a content entity.
	$config = \Drupal::getContainer()->get('config.factory')->getEditable('advtour_ui.settings');
	$config->set('intermedia','thumbnail')->save();
	$form['imagearray'] = array(
	'#title' => t('Local Computer Image'),
	'#type' => 'managed_file',
	'#prefix'	=> '<h1>Dummy prefix</h1>',
	'#suffix'	=> '<h1>Dummy suffix</h1>',
	'#description' => t('<div class="managed_file_imagewrapper"></div><br/>Although the uploaded image will be displayed on this page fill in alternative text.'),
	'#default_value' => $this->get('imagearray'),
	'#upload_validators'  => array(
		'file_validate_extensions' => array('gif png jpg jpeg'),
		'file_validate_size' => array(25600000),
	),
	'#upload_location' => 'public://images/',
	'#required' => FALSE,
	);
	
	// Load the file.
	$imageid = $this->get('imagearray');
	$file = file_load($imageid[0]);
	// Change status to permanent.
	if(gettype($file) == 'object'){
	$file->status = FILE_STATUS_PERMANENT;	
	// Save.
	$file->save();
	$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
	$file->setOwner($user);
	// Record the module (in this example, user module) is using the file. 
	\Drupal::service('file.usage')->add($file, 'advtour', 'advtour', $this->get('id')); 
	$_SESSION['intermedia'] = 'nothing';
	//drupal_set_message('File Saved');
	} else {
		//drupal_set_message('File is not an allowed type of gif png jpg jpeg and is currently of type: ' . gettype($file),'warn');
	}  
			
	$form['alt'] = array(
      '#type' => 'textfield',
	  '#size' => 80,
      '#title' => t('Alt Text'),
      '#required' => FALSE,
      '#default_value' => $this->get('alt'),
	  '#description' => t('The alt text which is used for the image in this Tip'),
    );

  /**
   * Overrides \Drupal\advtour\Plugin\advtour\advtour\TipPluginInterface::getOutput().
   */
   
  public function getOutput() {
    global $base_url;
	$_SESSION['intermedia'] = 'nothing';
	$imageid = $this->get('imagearray');
	$file = file_load($imageid[0]);
    $output = '<h2 class="advtour-tip-label" id="advtour-tip-' . $this->get('ariaId') . '-label">' . $this->get('label') . '</h2>';
	$output .= '<p class="advtour-tip-image" id="advtour-tip-' . $this->get('ariaId') . '-contents">' . '<img src="' . $base_url . '/sites/default/files/images/' . $file->getFilename() . '" alt="' . $this->get('alt') . '" /></p>';
	
	return array('#markup' => $output);
  }

Hope it helps. (Don't worry about the thumbnail signalling code as it has no bearing on uploading.)

Oualid-EZR’s picture

ah thankyou for helping but i have other question plz
I want to create Module (a contact form ) with code from content type already created from the back-office, i want to start creating but i dont know how, if some one know how plz help :D

thank you.

the content type hase
a title
email
name
message

slewazimuth’s picture

Here is a link to many examples which will help you: https://www.drupal.org/project/examples

jasodeep_chatterjee’s picture

file_load() method in deprecated in D8. So is this the correct approach to manage files in D8 ?

slewazimuth’s picture

file_load() simply became \Drupal\file\Entity\File::load() and far as the previous code goes $file = file_load($imageid[0]); became $file = \Drupal\file\Entity\File::load($imageid[0]); which for that code works fine. Could it have been written differently? Of course it could. In this case correct or incorrect was simply does it work or not.